<p>首先,您的代码包含几个错误:</p>
<ol>
<li><p>在<code>getheadersonly</code>的每个请求中,都安装一个新的全局urlopener,然后在<code>urllib2.urlopen</code>的后续调用中使用它</p></li>
<li><p>您发出两个HTTP请求以获取响应的两个不同属性。</p></li>
<li><p><code>urllib2.HTTPRedirectHandler.http_error_302</code>的实现并不是那么简单,我不理解它如何首先防止重定向。</p></li>
</ol>
<p>基本上,您应该了解每个处理程序都安装在一个opener中以处理某种类型的响应。<code>urllib2.HTTPRedirectHandler</code>可以将某些http代码转换为重定向。如果不需要重定向,请不要将重定向处理程序添加到打开程序中。如果不想打开ftp链接,请不要添加<code>FTPHandler</code>等</p>
<p>您只需要创建一个新的opener并在其中添加<code>urllib2.HTTPHandler()</code>,将请求定制为“HEAD”请求并将请求的实例传递给opener,读取属性并关闭响应。</p>
<pre><code>class HeadRequest(urllib2.Request):
def get_method(self):
return 'HEAD'
def getheadersonly(url, redirections=True):
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
if redirections:
# HTTPErrorProcessor makes HTTPRedirectHandler work
opener.add_handler(urllib2.HTTPErrorProcessor())
opener.add_handler(urllib2.HTTPRedirectHandler())
try:
res = opener.open(HeadRequest(url))
except urllib2.HTTPError, res:
pass
res.close()
return dict(code=res.code, headers=res.info(), finalurl=res.geturl())
</code></pre>