Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain login session while logging in using Python Script

I want to login to Ideone.com using python script and then extract stuff from my own account using subsequent requests using python script. This is what I used for logging in to the website:

import requests
import urllib
from bs4 import BeautifulSoup

url='http://ideone.com/account/login/'
body = {'username':'USERNAME', 'password':'PASSWORD'}

s = requests.Session()
loginPage = s.get(url)
soup = BeautifulSoup(loginPage.text)

r = s.post(soup.form['action'], data = body)
print r

This code successfully logs me in to my ideone account. But if I make subsequent call(using BeautifulSoup) to access my account details, it send me HTML of login page again.

How can I save session for a particular script so that it accepts the subsequent calls? Thanks in advance and sorry if this has been asked earlier.

like image 740
Sahil Avatar asked Nov 01 '22 18:11

Sahil


1 Answers

Here is how we can do this:

from requests import session
from bs4 import BeautifulSoup

payload = {
    'action'   : 'login',
    'username' : 'USERNAME',
    'password' : 'PASSWORD'
}
login_url='http://ideone.com/account/login/'

with session() as c:
    c.post(login_url, data = payload)
    request = c.get('http://ideone.com/myrecent')
    print request.headers
    print request.text
like image 187
Sahil Avatar answered Nov 15 '22 04:11

Sahil