How to use Python to login to a webpage and retrieve cookies for later usage?
Here's a version using the excellent requests library:
from requests import sessionpayload = { 'action': 'login', 'username': USERNAME, 'password': PASSWORD}with session() as c: c.post('http://example.com/login.php', data=payload) response = c.get('http://example.com/protected_page.php') print(response.headers) print(response.text)
import urllib, urllib2, cookielibusername = 'myuser'password = 'mypassword'cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))login_data = urllib.urlencode({'username' : username, 'j_password' : password})opener.open('http://www.example.com/login.php', login_data)resp = opener.open('http://www.example.com/hiddenpage.php')print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.