问题:在Python请求库的get方法中使用标头

因此,我最近偶然发现了这个用于在Python中处理HTTP请求的强大库;在此处找到http://docs.python-requests.org/en/latest/index.html

我喜欢使用它,但是我不知道如何在我的get请求中添加标题。救命?

So I recently stumbled upon this great library for handling HTTP requests in Python; found here 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?


回答 0

根据api,标头都可以使用request.get传递:

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

According to the api, the headers can all be passed in using requests.get:

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

回答 1

根据您链接的页面上的文档,您似乎很简单(强调我的)。

requests.get(URL,params = None,headers = None,Cookies = None,auth = None,timeout = None)

发送GET请求。返回Response对象。

参数:

  • url –新Request对象的URL 。
  • params –(可选)与一起发送的GET参数字典Request
  • 标头-(可选)与一起发送的HTTP标头字典Request
  • cookies –(可选)与一起发送的CookieJar对象 Request
  • auth –(可选)AuthObject以启用基本HTTP身份验证。
  • 超时–(可选)浮动,描述请求的超时。

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)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

回答 2

这个答案告诉我,您可以为整个会话设置标题:

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'})

奖励:会话还可以处理Cookie。

This answer taught me that you can set headers for an entire 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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。