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

Bre*_*dly 122 python http-request python-requests

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

我喜欢使用它,但我无法弄清楚如何在我的获取请求中添加标题.救命?

cwa*_*ole 217

根据api,标题都可以使用requests.get传入:

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

  • 您可以检查发送的http请求标头:print(r.request.headers) (11认同)
  • @Breedly正确的地方,正确的时间。我一生的故事:大量的好运加上大量的辛勤工作。 (2认同)

Joh*_*ess 33

根据您链接的页面上的文档(强调我的),看起来非常简单.

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

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

参数:

  • url - 新Request对象的URL .
  • params - (可选)用于发送的GET参数字典Request.
  • headers - (可选)用于发送的HTTP头的字典Request.
  • cookies - (可选)用于发送的CookieJar对象 Request.
  • auth - (可选)AuthObject以启用基本HTTP身份验证.
  • timeout - (可选)Float描述请求的超时.

  • 谢谢,但我真的不太了解Python的语法.只是一种学习.下次假装我一无所知,并且像上面的老兄一样阅读了API. (3认同)

Cee*_*man 19

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

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'})
Run Code Online (Sandbox Code Playgroud)

奖励:会话还处理cookie.


小智 15

  1. 访问http://myhttpheader.com

  2. 复制属性 - 通常是“Accept-Language”和“User-Agent”。

  3. 将它们包装在字典中:

    headers = { 'Accept-Language' : content-copied-from-myhttpheader,
                'User-Agent':content-copied-from-myhttpheader}
    
    Run Code Online (Sandbox Code Playgroud)
  4. 在您的请求中传递标头

    requests.get(url=your_url,headers=headers)
    
    Run Code Online (Sandbox Code Playgroud)