您可以使用python请求库获取请求标头吗?

时间:2020-02-19 13:15:49

标签: python python-requests header

我正在使用python请求库从网站获取所有标头,但是请求似乎只在获取响应标头,并且我还需要请求标头。

是否可以在请求库中获取请求标头,还是应该使用其他库来获取标头?

我的代码:

import requests

r = requests.get("https://google.com", allow_redirects = False)

for key in r.headers:
    print(key, ": ", r.headers[key])

输出:

Location :  https://www.google.com/
Content-Type :  text/html; charset=UTF-8
Date :  Wed, 19 Feb 2020 13:08:27 GMT
Expires :  Fri, 20 Mar 2020 13:08:27 GMT
Cache-Control :  public, max-age=2592000
Server :  gws
Content-Length :  220
X-XSS-Protection :  0
X-Frame-Options :  SAMEORIGIN
Alt-Svc :  quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000

1 个答案:

答案 0 :(得分:1)

响应对象包含一个请求对象,它是产生响应的请求。

可以通过响应对象的requests.models.PreparedRequest属性访问此request对象,其标头位于请求对象的属性headers中。

请参见以下示例:

>>> import requests
>>> r = requests.get("http://google.com")
>>> r.request.headers
{'Connection': 'keep-alive', 'User-Agent': 'python-requests/2.22.0', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate'}