Question: Log in with Python requests and csrf token


Log in with Python requests and csrf token

Answers 0
Added at 2016-12-20 00:12

So here is what I have:

 with requests.Session() as s:
    # 1) get the csrf
    start_page = s.get(login_url)
    matchme = r'meta name="csrf-token" content="(.*)"/'
    csrf =, str(start_page.text))
    csrf =
    csrf = csrf[:csrf.find('"')]
    print csrf

    # 2) post user/pw/csrf
    signin = dict(_csrf=csrf, username='user', password='pw')
    r =, data=signin)

First part is to open the login page and get the csrf from header. Second part is to post the username, password, and _csrf. And I'm unable to login. It stays at the login page.

The form data when I inspect the login on the browser looks like:

Form Data
 _csrf: .......

Problem is the csrf form the first part is always different from the csrf (print r.text) on the second part. Seems like the post starts a different session and csrf gets a refresh.

How do I fix this? Thanks

Source Show
◀ Wstecz