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

我喜欢使用它,但我不知道如何向我的get请求添加头文件。帮助吗?


看起来很简单,根据你链接的页面上的文档(重点是我的)。

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()传递进来:

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

这个回答告诉我,你可以为整个会话设置头信息:

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。

访问http://myhttpheader.com 复制属性——通常是'Accept-Language'和'User-Agent'。 用字典把它们包起来: headers = {'Accept-Language': content- copy -from-myhttpheader, “用户代理”:content-copied-from-myhttpheader} 在请求中传递头信息 requests.get (url = your_url头=标题)