今天,我实际上需要从http-头响应中检索数据。但是因为我以前从来没有这样做过,而且你在Google上也找不到很多关于这方面的信息。我决定在这里提问。
那么,实际的问题是:如何在python中打印http-头响应数据?我正在Python3.5中使用requests模块,还没有找到这样的方法。
发布于 2016-06-03 14:09:46
更新:基于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'
}特别是文件说明:
不过,字典是特别的:它只是为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'但也就如何在实践中通过重定向到文件等方式并使用不同的方法提供建议:
使用Response.iter_content将处理许多在直接使用Response.raw时必须处理的问题。
发布于 2016-06-03 14:11:05
像这样的事怎么样:
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')发布于 2019-08-09 20:04:49
下面是如何获得--使用您提到的请求库(在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))https://stackoverflow.com/questions/37616460
复制相似问题