如何在 Python 2 中发送 HEAD HTTP 请求?
- 2025-01-09 08:46:00
- admin 原创
- 114
问题描述:
我在这里尝试获取给定 URL 的标头,以便确定 MIME 类型。http://somedomain/foo/
例如,我希望能够查看是否会返回 HTML 文档或 JPEG 图像。因此,我需要弄清楚如何发送 HEAD 请求,以便我可以读取 MIME 类型而无需下载内容。有人知道这样做的简单方法吗?
解决方案 1:
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
解决方案 2:
编辑:这个答案有效,但是现在你应该只使用下面其他答案中提到的请求库。
使用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)
来获取特定的标题。
解决方案 3:
必修Requests
方式:
import requests
resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers
解决方案 4:
我相信也应该提到Requests库。
解决方案 5:
只是:
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'
...
链接文本
解决方案 6:
为了完整性,使用httplib得到一个与接受的答案等同的 Python3 答案。
它基本上是相同的代码,只是库不再称为httplib,而是http.client
from http.client import HTTPConnection
conn = HTTPConnection('www.google.com')
conn.request('HEAD', '/index.html')
res = conn.getresponse()
print(res.status, res.reason)
解决方案 7:
import httplib
import urlparse
def unshorten_url(url):
parsed = urlparse.urlparse(url)
h = httplib.HTTPConnection(parsed.netloc)
h.request('HEAD', parsed.path)
response = h.getresponse()
if response.status/100 == 3 and response.getheader('Location'):
return response.getheader('Location')
else:
return url
解决方案 8:
另外,使用 httplib(至少在 2.5.2 上)时,尝试读取 HEAD 请求的响应将阻塞(在 readline 上)并随后失败。如果您没有对响应发出读取,则无法在连接上发送另一个请求,您需要打开一个新请求。或者接受请求之间的长时间延迟。
解决方案 9:
我发现 httplib 比 urllib2 稍快。我对两个程序进行了计时 - 一个使用 httplib,另一个使用 urllib2 - 向 10,000 个 URL 发送 HEAD 请求。httplib 快了几分钟。httplib 的总统计数据为:实际 6m21.334s 用户 0m2.124s 系统 0m16.372s
urllib2的总体统计数据为:实际 9m1.380s 用户 0m16.666s 系统0m28.565s
还有其他人对此有意见吗?
解决方案 10:
还有另一种方法(类似于 Pawel 的答案):
import urllib2
import types
request = urllib2.Request('http://localhost:8080')
request.get_method = types.MethodType(lambda self: 'HEAD', request, request.__class__)
只是为了避免在实例级别有不受限制的方法。
解决方案 11:
可能更简单:使用 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 通常不直接使用。
扫码咨询,免费领取项目管理大礼包!