在Python请求库的get方法中使用头

2024-04-20 13:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我最近偶然发现了这个用Python处理HTTP请求的伟大库;可以在这里找到http://docs.python-requests.org/en/latest/index.html

我喜欢使用它,但是我不知道如何向get请求添加头。帮忙?


Tags: orghttpdocsgetindexhtmlrequestslatest
3条回答

This answer教我可以为整个会话设置标题:

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

奖金:Sessions also handle cookies.

根据你链接的页面上的docs(强调我的页面),看起来很简单。

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.

根据api,可以使用requests传递所有头。get:

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

相关问题 更多 >