簡體   English   中英

使用帶有 Python 請求庫的 get 方法的標頭

[英]Using headers with the Python requests library's get method

所以我最近偶然發現了這個很棒的庫,用於處理 Python 中的 HTTP 請求; 在這里找到http://docs.python-requests.org/en/latest/index.html

我喜歡使用它,但我不知道如何將標頭添加到我的獲取請求中。 幫助?

根據API ,標頭都可以使用requests.get傳入:

import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})

根據您鏈接的頁面上的文檔(強調我的),看起來很簡單。

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

發送 GET 請求。 返回Response object。

參數:

  • url – URL 用於新Request object。
  • params –(可選)與Request一起發送的 GET 參數字典。
  • headers - (可選)HTTP 標題字典與Request一起發送。
  • cookies –(可選)CookieJar object 與Request一起發送。
  • auth –(可選)AuthObject 以啟用基本 HTTP Auth。
  • timeout –(可選)描述請求超時的浮點數。

這個答案告訴我,您可以為整個 session 設置標題:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

獎勵: 會話還處理 cookies。

  1. Go 到http://myhttpheader.com
  2. 復制屬性 - 通常是“Accept-Language”和“User-Agent”。
  3. 將它們包裝在字典中:

headers = {'Accept-Language': content-copied-from-myhttpheader, 'User-Agent':content-copied-from-myhttpheader}

  1. 在您的請求中傳遞標頭 requests.get(url=your_url,headers=headers)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM