403禁止,CSRF验证失败。请求中止。 python请求

时间:2016-12-13 09:40:02

标签: python python-requests

import requests
import json
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36'}
post_data={"q":"","filters":{"sizes":["Large","MNE"],"sectors":[18],"countries":[228],"regions":["Northern America"],"years":[2015],"types":[]},"page":1}


with requests.Session() as s:
    for_cookies=s.get('http://database.globalreporting.org/search')
    # print(for_cookies.content)
    p = s.post('http://database.globalreporting.org/search/ajax/',data=json.dumps(post_data), headers=headers)
    print(p.content)

我的Chrome可以访问该网站,但我的代码不能。如何让我的代码能够访问该网站? enter image description here

2 个答案:

答案 0 :(得分:3)

我已经包含了csrf令牌并试图调用它。但我认为Django网站必须使用,

if not request.is_ajax():
    return HttpResponse('Only ajax request')

因为我尝试了代码,

import requests

with requests.Session() as client:
    for_cookies=client.get('http://database.globalreporting.org/search')
    csrf = client.cookies['csrftoken']
    print csrf
    post_data={"csrfmiddlewaretoken": csrf, "q":"","filters":{"sizes":["Large","MNE"],"sectors":[18],"countries":[228],"regions":["Northern America"],"years":[2015],"types":[]},"page":1}
    r = client.post('http://database.globalreporting.org/search/ajax/', data=post_data, headers=dict(Referer='http://database.globalreporting.org/search'))
    print r.text

我得到的回应是

YrZa9IIoFJZyXqeRXZnZ57s3vaoCUCul
Only ajax request

通常,在这些情况下您必须使用csrf令牌。但是我们可以配置是否仅使用ajax。

希望我的回答可以帮到你。

答案 1 :(得分:1)

您需要将CSRF令牌值添加到标题中:

with requests.Session() as s:
    for_cookies=s.get('http://database.globalreporting.org/search')

    headers =  
    {'X-CSRFToken': for_cookies.headers['Set-Cookie'].split('=')[1].split(';')[0],
    'Referer': 'http://database.globalreporting.org/search/',
    'X-Requested-With':'XMLHttpRequest'}

    p = s.post('http://database.globalreporting.org/search/ajax/',data=json.dumps(post_data), headers=headers)
    print(p.content)

尝试此代码,如有任何问题,请告知我

相关问题