简体   繁体   English

使用带有 Python 请求库的 get 方法的标头

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

So I recently stumbled upon this great library for handling HTTP requests in Python;所以我最近偶然发现了这个很棒的库,用于处理 Python 中的 HTTP 请求; found here http://docs.python-requests.org/en/latest/index.html .在这里找到http://docs.python-requests.org/en/latest/index.html

I love working with it, but I can't figure out how to add headers to my get requests.我喜欢使用它,但我不知道如何将标头添加到我的获取请求中。 Help?帮助?

According to the API , the headers can all be passed in using requests.get :根据API ,标头都可以使用requests.get传入:

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

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).根据您链接的页面上的文档(强调我的),看起来很简单。

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

Sends a GET request.发送 GET 请求。 Returns Response object.返回Response object。

Parameters:参数:

  • url – URL for the new Request object. url – URL 用于新Request object。
  • params – (optional) Dictionary of GET Parameters to send with the Request . params –(可选)与Request一起发送的 GET 参数字典。
  • headers – (optional) Dictionary of HTTP Headers to send with the Request . headers - (可选)HTTP 标题字典与Request一起发送。
  • cookies – (optional) CookieJar object to send with the Request . cookies –(可选)CookieJar object 与Request一起发送。
  • auth – (optional) AuthObject to enable Basic HTTP Auth. auth –(可选)AuthObject 以启用基本 HTTP Auth。
  • timeout – (optional) Float describing the timeout of the request. timeout –(可选)描述请求超时的浮点数。

This answer taught me that you can set headers for an entire session:这个答案告诉我,您可以为整个 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'})

Bonus: Sessions also handle cookies.奖励: 会话还处理 cookies。

  1. Go to http://myhttpheader.com Go 到http://myhttpheader.com
  2. copy attributes - typically 'Accept-Language' and 'User-Agent'.复制属性 - 通常是“Accept-Language”和“User-Agent”。
  3. Wrap them in the dictionary:将它们包装在字典中:

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

  1. pass headers in your request requests.get(url=your_url,headers=headers)在您的请求中传递标头 requests.get(url=your_url,headers=headers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM