我試圖將表單數據發佈到URL。我沒有得到預期的響應,並對來自請求模塊(2.6.2)的一些信息感到好奇。以下是POST方法:Python請求模塊不使用post方法
>>> response = requests.post(url, data={'uname':user, 'pwd':password,'phrase':'','submit':True})
正如你可以看到我使用的方法post()
,所以我預期的方法是POST
。對象data
的鍵匹配表單元素的名稱。網址是表單操作。
>>> vars(response.request)
{'method': 'GET', 'body': None, '_cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>, 'headers': {'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Connection': 'keep-alive'}, 'hooks': {'response': []}, 'url': url}
的response.request
屬性應包含有關在此響應發送的請求信息。這是method
財產是GET
,我預計POST
。該URL看起來正確。該頁面預計會返回別的東西,如果表單帖子雖然,奇怪,我會檢查請求標題。
>>> response.request.headers
{'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Connection': 'keep-alive'}
>>>
那些看起來不錯,等一下!我的表單數據在哪裏?爲什麼它沒有與請求一起發送?我查看歷史記錄,發現我正在重定向。這次我加allow_redirects=False
給我的post()
電話。然後檢查response.request
對象及其標題。
>>> vars(response.request)
{'method': 'POST', 'body': 'phrase=&pwd=****&uname=****&submit=True', '_cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>, 'headers': {'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Content-Length': '56', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'hooks': {'response': []}, 'url': 'http://myurl.com/path/to/script.php'}
這一次這是一個POST
,這似乎是正確的。我感覺我正走在正確的軌道上。奇怪的是,body
屬性看起來像一個查詢字符串,不像我期望的表單帖子。
>>> response.request.headers
{'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Content-Length': '56', 'Accept': '*/*', 'Connection': 'keep-alive'}
這些標題,在標題中也沒有表單數據。這是什麼? 'Content-Type': 'application/x-www-form-urlencoded'
?這就是爲什麼我的表單數據看起來像查詢字符串?普通的內容類型是什麼?它與Chrome瀏覽器打出相同網址的報告類型相同,因此我懷疑這是問題所在。
如果這看起來都不對,他們可能會很聰明,並拒絕從非本地來源的權利?我主要關心的是表單數據是body
屬性中的一個字符串,這似乎是錯誤的。如果沒有,我可以變得聰明,並設置HTTP頭源?
我試着用'。員額(頭= { '原點':..., '主機':...,...})欺騙頭'並沒有什麼區別。 – ToothlessRebel