如何在Python中打印出http-response标头

Nao*_*omi 5 python header http response

今天我实际上需要从http-header响应中检索数据.但是因为我以前从未这样做过,而且你在谷歌上找不到这个.我决定在这里问我的问题.

所以实际问题:如何在python中打印http-header响应数据?我正在使用请求模块在Python3.5中工作,还没有找到一种方法来做到这一点.

Dil*_*ant 16

更新:根据 OP 的评论,只需要响应头。更简单的写在下面的请求模块文档中:

我们可以使用 Python 字典查看服务器的响应头:

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}
Run Code Online (Sandbox Code Playgroud)

尤其是文档说明:

不过,这本字典很特别:它只是为 HTTP 标头而制作的。根据 RFC 7230,HTTP 标头名称不区分大小写。

因此,我们可以使用任何我们想要的大小写来访问标题:

并继续解释有关 RFC 合规性的更多聪明之处。

请求的文件中指出:

使用 Response.iter_content 将处理许多您在直接使用 Response.raw 时必须处理的内容。流式下载时,以上是检索内容的首选和推荐方式。

它提供了以下示例:

>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
Run Code Online (Sandbox Code Playgroud)

但也提供了如何通过重定向到文件等并使用不同的方法在实践中做到这一点的建议:

使用 Response.iter_content 将处理很多你在直接使用 Response.raw 时必须处理的事情


Nep*_*der 7

这样的事情怎么样:

import urllib2
req = urllib2.Request('http://www.google.com/')
res = urllib2.urlopen(req)
print res.info()
res.close();
Run Code Online (Sandbox Code Playgroud)

如果您要在标题中查找特定内容:

For Date: print res.info().get('Date')
Run Code Online (Sandbox Code Playgroud)

  • 这个答案有 python3 版本吗? (2认同)

小智 5

简单的

import requests

site = "https://www.google.com"
headers = requests.get(site).headers
print(headers)
Run Code Online (Sandbox Code Playgroud)

如果你想要一些具体的东西

print(headers["domain"]) 
Run Code Online (Sandbox Code Playgroud)


Jos*_*eia 5

以下是使用您提到的请求库(在 Python3 中实现)获取响应标头的方法:

import requests

url = "https://www.google.com"
response = requests.head(url)
print(response.headers) # prints the entire header as a dictionary
print(response.headers["Content-Length"]) # prints a specific section of the dictionary
Run Code Online (Sandbox Code Playgroud)

重要的是使用.head()而不是.get()否则您将像提到的其余答案一样检索整个文件/页面。

如果您希望检索需要身份验证的 URL,您可以将上述内容替换为response

response = requests.head(url, auth=requests.auth.HTTPBasicAuth(username, password))
Run Code Online (Sandbox Code Playgroud)