2016-12-13 215 views
1
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) 

我的鉻可以訪問網站,但我的代碼不能。如何讓我的代碼能夠訪問該網站? enter image description here403禁止並且CSRF驗證失敗。請求中止。蟒蛇的請求

+0

你沒有發送csrf令牌 –

回答

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) 

試試這個代碼,讓我知道在

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。

希望我的回答能幫助你。

相關問題