如何使用请求模块修复“ CSRF验证失败”

时间:2019-05-07 13:57:28

标签: python python-requests

我正在使用python请求库,并且尝试登录到https://www.udemy.com/join/login-popup/,问题是当我使用以下标头时:

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}  

它返回CSRF verification failed. Request aborted

当我将其更改为:

headers = {'Referer': url}    

它返回Please verify that you are a human

有什么建议吗?

我的代码:

import requests


with requests.session() as s:
    url = 'https://www.udemy.com/join/login-popup/'
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) '
                             'Chrome/74.0.3729.131 Safari/537.36'}
    request = s.get(url, headers=headers)
    cookies = dict(cookies=request.cookies)
    csrf = request.cookies['csrftoken']
    data_login = {'csrfmiddlewaretoken': csrf, 'locale': 'en_US', 'email': 'myemail',
                  'password': 'maypassword'}
    request = s.post(url, data=data_login, headers={'Referer': url}, cookies=cookies['cookies'])
    print(request.content)

1 个答案:

答案 0 :(得分:0)

您当前的代码有几个问题:

  1. 您正在使用的标头缺少一些内容

  2. 您为csrfmiddlewaretoken传递的值不正确

  3. 在使用requests.session()时,您不应该手动添加Cookie (在这种情况下)

尝试以下代码:

import requests
from bs4 import BeautifulSoup


with requests.session() as s:
    url = 'https://www.udemy.com/join/login-popup/'
    headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0", "Referer": "https://www.udemy.com/join/login-popup/", "Upgrade-Insecure-Requests": "1"}

    request = s.get(url, headers=headers)
    soup = BeautifulSoup(request.text, "lxml")
    csrf = soup.find("input",{"name":"csrfmiddlewaretoken"})["value"]

    data_login = {'csrfmiddlewaretoken': csrf, 'locale': 'en_US', 'email': 'myemail@test.com','password': 'maypassword'}
    request = s.post(url, data=data_login, headers=headers)
    print(request.content)

(PS:我正在使用Beautifulsoup库来查找csrfmiddlewaretoken的值)

希望这会有所帮助