Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python to login to a webpage and retrieve cookies for later usage?

People also ask

How do I automatically login to a website using python?

Stepwise Implementation: First of all import the webdrivers from the selenium library. Find the URL of the login page to which you want to logged in. Provide the location executable chrome driver to selenium webdriver to access the chrome browser.

How do I store login information in cookies?

For login cookies, there are two common methods of storing login information in cookies: a signed cookie or a token cookie. Signed cookies typically store the user's name, maybe their user ID, when they last logged in, and whatever else the service may find useful.

How do you implement cookies in Python?

We use Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.


Here's a version using the excellent requests library:

from requests import session

payload = {
    '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, cookielib

username = '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.