实际上,似乎urllib2可以执行HTTP HEAD请求。
上面@reto链接到的问题说明了如何获取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
接受编码:身份
主办: 一点点地
连接方式:关闭
用户代理:Python-urllib / 2.7
HTTP / 1.1 301已移动
服务器:nginx
日期:2012年2月19日,星期日 格林尼治标准时间13:20:56
内容类型:text / html; 字符集= utf-8
缓存控制:私有; 最大年龄= 90
位置: [http://www.kidsidebyside.org/?p=445]
MIME版本:1.0
内容长度:127
连接方式:关闭
Set-Cookie: _bit = 4f40f738-00153-02ed0-421cf10a; domain = .bit.ly; expires = Fri Aug 17 13:20:56 2012; path = /; HttpOnly
但是,如另一个问题中的一个注释中所述,如果所讨论的URL包含重定向,则urllib2将向目标而不是HEAD发送GET请求。 如果您确实只想发出HEAD请求,则这可能是一个主要缺点。
上面的请求涉及重定向。 这是到目的地的请求,由Wireshark捕获:
GET / 2009/05 /与我们/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)
这具有将HEAD请求用于初始HTTP请求和重定向到目标URL的优点。
这是第一个请求:
HEAD / doFeT HTTP / 1.1
主持人:bit.ly
接受编码:gzip, 放气
用户代理:Python-httplib2 / 0.7.2(gzip)
这是到目的地的第二个请求:
HEAD / 2009/05 /与我们/HTTP/1.1绘制圆的统一体
主持人:www.kidsidebyside.org
接受编码:gzip,放气
用户代理:Python-httplib2 / 0.7.2(gzip)