如何在Python 2中发送HEAD HTTP请求?
我在这里尝试做的是获取给定URL的标头,以便确定MIME类型。我希望能够查看http:// somedomain / foo /
是否将返回HTML文档或者JPEG图像。因此,我需要弄清楚如何发送HEAD请求,以便无需下载内容即可读取MIME类型。有人知道这样做的简单方法吗?
解决方案
编辑:这个答案有效,但是现在我们应该使用下面其他答案提到的请求库。
使用httplib。
>>> import httplib >>> conn = httplib.HTTPConnection("www.google.com") >>> conn.request("HEAD", "/index.html") >>> res = conn.getresponse() >>> print res.status, res.reason 200 OK >>> print res.getheaders() [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
还有一个" getheader(name)"来获取特定的标题。
可能更容易:使用urllib或者urllib2.
>>> import urllib >>> f = urllib.urlopen('http://google.com') >>> f.info().gettype() 'text/html'
f.info()是类似字典的对象,因此我们可以执行f.info()['content-type']等。
http://docs.python.org/library/urllib.html
http://docs.python.org/library/urllib2.html
http://docs.python.org/library/httplib.html
文档指出,通常不直接使用httplib。
顺便说一句,当使用httplib时(至少在2.5.2上),尝试读取HEAD请求的响应将阻塞(在读取行中),随后失败。如果未在响应中发出已读消息,则无法在连接上发送另一个请求,则需要打开一个新请求。或者接受两次请求之间的长时间延迟。
urllib2可用于执行HEAD请求。这比使用httplib更好,因为urllib2为我们解析URL,而不是要求我们将URL分为主机名和路径。
>>> import urllib2 >>> class HeadRequest(urllib2.Request): ... def get_method(self): ... return "HEAD" ... >>> response = urllib2.urlopen(HeadRequest("http://google.com/index.html"))
标头可以通过response.info()像以前一样使用。有趣的是,我们可以找到重定向到的URL:
>>> print response.geturl() http://www.google.com.au/index.html
我发现httplib比urllib2快一点。我给两个程序计时,一个使用httplib计时,另一个使用urllib2将HEAD请求发送到10,000个URL。 httplib的速度快了几分钟。 httplib的总统计为:实际6分21.334秒
用户0m2.124s
sys 0m16.372s
urllib2的总统计为:真正的9m1.380s
用户0m16.666s
sys 0m28.565s
有人对此有意见吗?
只是:
import urllib2 request = urllib2.Request('http://localhost:8080') request.get_method = lambda : 'HEAD' response = urllib2.urlopen(request) response.info().gettype()
编辑:我刚开始意识到有httplib2:D
import httplib2 h = httplib2.Http() resp = h.request("http://www.google.com", 'HEAD') assert resp[0]['status'] == 200 assert resp[0]['content-type'] == 'text/html' ...
连结文字