Skip to content Skip to sidebar Skip to footer

Python Requests Login To Website Returns 403

I'm trying to use requests to login to a website but as you can guess I'm having a problem here's the the code that I'm using import requests EMAIL = '***' PASSWORD = '***' URL =

Solution 1:

The login page uses a CSRF token to prevent cross-site scripting attacks. You'll need to retrieve that token first.

The login page sets a cookie with the same token, we need to load the login page and grab that token first, before we pass this on to the login POST:

client = requests.session()

# Retrieve the CSRF token first
client.get(URL)  # sets the cookie
csrftoken = client.cookies['csrftoken']

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken)
r = client.post(URL, data=login_data, headers={"Referer": "foo"})

Solution 2:

as the error message suggests, you are missing the csrf token

you need to GET the login page first, read the csrf token and POST that back along with the rest of your form data

Post a Comment for "Python Requests Login To Website Returns 403"