本文作者:寒菱
本文鏈接:https://www.cnblogs.com/gaoyongjian/p/13845850.html
序
如題离陶,在使用 requests 發(fā)送 post 請(qǐng)求時(shí)保持 headers 的順序不變
問題來(lái)源于 http://match.yuanrenxue.com/match/3 這個(gè)網(wǎng)站
在抓包時(shí)發(fā)現(xiàn)每次獲取數(shù)據(jù)前都會(huì)發(fā)送一個(gè) post 請(qǐng)求去獲取cookies
在模擬時(shí)卻發(fā)現(xiàn)怎么都無(wú)法獲取cookies
通過 fiddler 查看發(fā)現(xiàn)是 headers 的順序有問題,
通過 postman 調(diào)整 headers 的順序延刘,模擬發(fā)送請(qǐng)求,確定是 headers 順序的問題
問題定位
通過 fiddler 查看發(fā)現(xiàn)可能是 headers 的順序有問題远剩,
通過 postman 調(diào)整 headers 的順序子库,模擬發(fā)送請(qǐng)求睁冬,確定是 headers 順序的問題
解決方案
<code-box id="6PCfYY" style="padding: 0px; margin: 0px; position: relative; display: block;"><pre id="pre-6PCfYY" class="mCustomScrollbar _mCS_1 mCS-autoHide" style="padding: 10px !important; margin: 5px 0px; overflow: visible; touch-action: pinch-zoom; font-size: 14px !important; font-weight: 400; font-family: "Ubuntu Mono", monospace !important; white-space: pre; overflow-wrap: break-word; border-radius: 4px !important; word-break: break-all; counter-reset: itemcounter 0; color: rgb(0, 0, 0); max-height: 70vh; background-color: rgb(246, 248, 250); position: relative;">
<code-pre class="code-pre code-pre-line" id="pre-82w5Dy" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);">import requests
url = "xxx"
headers = {
"Host": "match.yuanrenxue.com",
"Connection": "keep-alive",
"Content-Length": "0",
"Origin": "http://match.yuanrenxue.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
"Accept": "/",
"Referer": "http://match.yuanrenxue.com/match/3",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
}
先session
session=requests.Session()
后session clear,clear這個(gè)是比較關(guān)鍵的寫法徒河。
session.headers.clear()
session.headers.update(
headers
)
resp=session.post(url)</code-pre>
</pre></code-box>
謹(jǐn)記
之前從未遇到過這個(gè)問題系馆,