How to programmatically log in to website App using Python

For this example, we are going to log in to a Django application. If it is another type of application, you only have to check the needed login form fields.

import requests
from bs4 import BeautifulSoup

USERNAME = 'username'  # put correct username here
PASSWORD = 'password'  # put correct password here

URL = '' # Change to your domain
LOGINURL = URL + '/login/'  # Change to your app login url
DATAURL = URL + 'url_data' # Change 

session = requests.session()

req_headers = {
    'Content-Type': 'application/x-www-form-urlencoded'

# to get csrfToken
r = session.get(LOGINURL,  headers=req_headers, allow_redirects=False)

soup = BeautifulSoup(r.text)
csrfToken = soup.find('input', attrs={'name': 'csrf_token'})['value']

formdata = {
    'username': USERNAME,
    'password': PASSWORD,
    'csrf_token': csrfToken,
# login post
r =, data=formdata, headers=req_headers, allow_redirects=False)

# We are logged in and we can read data
r2 = session.get(DATAURL)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s