其实看来urllib2可以做一个HTTP HEAD请求。
上面@reto 链接到的question 显示了如何让 urllib2 执行 HEAD 请求。
这是我的看法:
import urllib2
# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)
try:
response = urllib2.urlopen(request)
response_headers = response.info()
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response_headers.dict
except urllib2.HTTPError, e:
# Prints the HTTP Status code of the response but only if there was a
# problem.
print ("Error code: %s" % e.code)
如果您使用 Wireshark 网络协议分析器之类的工具进行检查,您会发现它实际上发送的是 HEAD 请求,而不是 GET。
这是来自上述代码的 HTTP 请求和响应,由 Wireshark 捕获:
HEAD /doFeT HTTP/1.1
接受编码:身份
主机:
bit.ly
连接:关闭
用户代理:Python-urllib/2.7
HTTP/1.1 301 已移动
服务器:nginx
日期:2012 年 2 月 19 日,星期日
格林威治标准时间 13:20:56
内容类型:文本/html;字符集=utf-8
缓存控制:私有; max-age=90
位置:
http://www.kidsidebyside.org/?p=445
MIME 版本:1.0
内容长度:127
连接:关闭
设置 Cookie:
_bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=2012 年 8 月 17 日星期五 13:20:56;path=/; HttpOnly
但是,正如另一个问题中的一个 cmets 所述,如果相关 URL 包含重定向,则 urllib2 将向目标发出 GET 请求,而不是 HEAD。如果您真的只想发出 HEAD 请求,这可能是一个主要缺点。
上述请求涉及重定向。这是 Wireshark 捕获的对目的地的请求:
GET /2009/05/come-and-draw-the-circle-of-unity-with-us/HTTP/1.1
接受编码:身份
主持人:www.kidsidebyside.org
连接:关闭
用户代理:Python-urllib/2.7
使用 urllib2 的替代方法是使用 Joe Gregorio 的 httplib2 库:
import httplib2
url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()
try:
response, content = http_interface.request(url, method="HEAD")
print ("Response status: %d - %s" % (response.status, response.reason))
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response.__dict__
except httplib2.ServerNotFoundError, e:
print (e.message)
这具有对初始 HTTP 请求和重定向到目标 URL 的请求都使用 HEAD 请求的优势。
这是第一个请求:
HEAD /doFeT HTTP/1.1
主机:bit.ly
接受编码:gzip,
放气
用户代理:Python-httplib2/0.7.2 (gzip)
这是第二个请求,发往目的地:
HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/HTTP/1.1
主持人:www.kidsidebyside.org
接受编码:gzip、deflate
用户代理:Python-httplib2/0.7.2 (gzip)