在Python 2中如何发送HEAD HTTP请求?

2024-04-23 06:56:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里要做的是获取给定URL的头,以便确定MIME类型。我想看看http://somedomain/foo/是否会返回HTML文档或JPEG图像。因此,我需要弄清楚如何发送HEAD请求,这样我就可以读取MIME类型,而不必下载内容。有人知道做这件事的简单方法吗?


Tags: 方法文档图像httpurl类型内容foo
3条回答

编辑:此答案有效,但现在您应该只使用下面其他答案中提到的requests库。


使用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)来获取特定的头。

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

必须的^{}方式:

import requests

resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers

相关问题 更多 >