python只使用urllib2获取头文件

时间:2012-03-27 13:47:05

标签: python urllib2

我必须使用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

使用回答thisthis的代码。但是,即使标志为False,此仍在执行重定向。我尝试了代码:

print getheadersonly("http://ms.com", redirections = False)['finalurl']
print getheadersonly("http://ms.com")['finalurl']

在两种情况下都给予morganstanley.com。这有什么不对?

2 个答案:

答案 0 :(得分:7)

首先,您的代码包含几个错误:

  1. getheadersonly的每个请求中,您安装了一个新的全局urlopener,然后在urllib2.urlopen

  2. 的后续调用中使用
  3. 您发出两个HTTP请求以获取响应的两个不同属性。

  4. urllib2.HTTPRedirectHandler.http_error_302的实施并非如此微不足道,我不明白它如何能够首先阻止重定向。

  5. 基本上,您应该了解每个处理程序都安装在一个开启器中以处理某种响应。 urllib2.HTTPRedirectHandler可以将某些http代码转换为重定向。如果您不想重定向,请不要在重定向中添加重定向处理程序。如果您不想打开ftp链接,请不要添加FTPHandler

    这就是你需要创建一个新的开启者并在其中添加urllib2.HTTPHandler(),将请求自定义为'HEAD'请求并将请求的实例传递给开启者,读取属性,以及关闭回应。

    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())
    

答案 1 :(得分:2)

您可以发送HEAD request using httplibHEAD请求与GET请求相同,但服务器不发送消息正文。

相关问题