今天我需要从http头响应中检索数据。但由于我之前从未这样做过,而且在Google上也很难找到相关信息。因此,我决定在这里提问。
所以我的问题是:如何在Python中打印http头响应数据?我正在使用Python3.5与requests模块,并且还没有找到一种方法来实现这个。
更新: 根据发帖者的评论,只需要响应头。 如下面文档中所述,使用Requests模块更加容易:
我们可以使用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'
}
特别是文档的注释:
这个字典很特别,因为它只为HTTP头而设计。根据RFC 7230,HTTP标头名称不区分大小写。
因此,我们可以使用任何大写或小写形式访问头部信息:
并继续解释了与RFC合规性相关的更多巧妙之处。
Requests文档中表示:
使用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'
但也提供了实际操作的建议,例如通过重定向到文件等方式并使用不同的方法来完成:
使用Response.iter_content将处理许多您在直接使用Response.raw时必须处理的内容。
以下是您如何使用requests库(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
使用.head()
而不是.get()
很重要,否则你将会像其他答案中提到的那样检索整个文件/页面。
如果您希望获取需要验证的URL,则可以将上述response
替换为以下内容:
response = requests.head(url, auth=requests.auth.HTTPBasicAuth(username, password))
这样的东西怎么样:
import urllib2
req = urllib2.Request('http://www.google.com/')
res = urllib2.urlopen(req)
print res.info()
res.close();
如果您正在寻找标题中的特定内容:
For Date: print res.info().get('Date')
import requests
site = "https://www.google.com"
headers = requests.get(site).headers
print(headers)
print(headers["domain"])
我正在使用urllib模块,以下是代码:
from urllib import request
with request.urlopen(url, data) as f:
print(f.getcode()) # http response code
print(f.info()) # all header info
resp_body = f.read().decode('utf-8') # response body
非常简单,您可以输入
print(response.headers)
print(requests.get('url').headers)
also u can use
print(requests.get('url').content)
req.headers
,就可以获取响应头啦 ;)