我必须使用urllib2实现一个只获取头的函数(不做get或POST)。以下是我的功能:
def getheadersonly(url, redirections = True):
if not redirections:
class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
http_error_301 = http_error_303 = http_error_307 = http_error_302
cookieprocessor = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor)
urllib2.install_opener(opener)
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
info = {}
info['headers'] = dict(urllib2.urlopen(HeadRequest(url)).info())
info['finalurl'] = urllib2.urlopen(HeadRequest(url)).geturl()
return info
使用来自答案this和this的代码。然而,即使标志是False
,这个也在进行重定向。我试过密码:
print getheadersonly("http://ms.com", redirections = False)['finalurl']
print getheadersonly("http://ms.com")['finalurl']
在这两种情况下它都给了morganstanley.com。这里怎么了?
你可以发送一个HEAD request using httplib。HEAD请求与GET请求相同,但服务器不发送then消息体。
首先,您的代码包含几个错误:
在
getheadersonly
的每个请求中,都安装一个新的全局urlopener,然后在urllib2.urlopen
的后续调用中使用它您发出两个HTTP请求以获取响应的两个不同属性。
urllib2.HTTPRedirectHandler.http_error_302
的实现并不是那么简单,我不理解它如何首先防止重定向。基本上,您应该了解每个处理程序都安装在一个opener中以处理某种类型的响应。
urllib2.HTTPRedirectHandler
可以将某些http代码转换为重定向。如果不需要重定向,请不要将重定向处理程序添加到打开程序中。如果不想打开ftp链接,请不要添加FTPHandler
等您只需要创建一个新的opener并在其中添加
urllib2.HTTPHandler()
,将请求定制为“HEAD”请求并将请求的实例传递给opener,读取属性并关闭响应。相关问题 更多 >
编程相关推荐