requests--請求頭設置


前戲

在我們進行自動化測試的時候,很多網站都會都請求頭做個校驗,比如驗證 User-Agent,看是不是瀏覽器發送的請求,如果我們不加請求頭,使用腳本訪問,默認User-Agent是python,這樣服務器如果進行了校驗,就會拒絕我們的請求。所以,在做自動化的時候,加上必要的請求頭是一個好習慣。

請求頭設置

使用requests庫添加請求頭很簡單,只需要傳一個headers參數就可以了

import requests

base_url = 'http://httpbin.org'

form_data = {"user": "zou", "pwd": '31500'}
form_header = {"User-Agent": "Chrome/68.0.3440.106"}  # 設置請求頭,字典格式
r = requests.post(base_url + '/post', data=form_data, headers=form_header)
print(r.url)  # 打印URL
print(r.status_code)
print(r.text)

結果:

http://httpbin.org/post
200
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "pwd": "31500", 
    "user": "zou"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "18", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Chrome/68.0.3440.106"
  }, 
  "json": null, 
  "origin": "112.10.81.210, 112.10.81.210", 
  "url": "https://httpbin.org/post"
}

查看請求頭

前面我們已經設置好了請求頭,我們可以使用r.request.headers來查看請求頭

import requests

base_url = 'http://httpbin.org'

form_data = {"user": "zou", "pwd": '31500'}
form_header = {"User-Agent": "Chrome/68.0.3440.106"}
r = requests.post(base_url + '/post', data=form_data, headers=form_header)

print(r.request.headers)  # 查看請求頭

結果:

{'User-Agent': 'Chrome/68.0.3440.106', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '18', 'Content-Type': 'application/x-www-form-urlencoded'}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM