【问题标题】:Making HTTP HEAD request with urllib2 from Python 2从 Python 2 使用 urllib2 发出 HTTP HEAD 请求
【发布时间】:2011-05-24 04:46:15
【问题描述】:

我正在尝试使用 Python 2 对页面进行 HEAD 请求。

我在努力

import misc_urllib2
.....
opender = urllib2.build_opener([misc_urllib2.MyHTTPRedirectHandler(), misc_urllib2.HeadRequest()])

misc_urllib2.py 包含

class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"


class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
    def __init__ (self):
        self.redirects = []

    def http_error_301(self, req, fp, code, msg, headers):  
        result = urllib2.HTTPRedirectHandler.http_error_301(
                self, req, fp, code, msg, headers)
        result.redirect_code = code
        return result

    http_error_302 = http_error_303 = http_error_307 = http_error_301

但我得到了

TypeError: __init__() takes at least 2 arguments (1 given)

如果我这样做

opender = urllib2.build_opener(misc_urllib2.MyHTTPRedirectHandler())

然后就可以正常使用了

【问题讨论】:

    标签: python python-2.7 urllib2 head


    【解决方案1】:

    您不应该将HeadRequest 添加到build_openeradd_handler 它应该这样调用

    opener = urllib2.build_opener(MyHTTPRedirectHandler)
    response = opener.open(HeadRequest(url))
    print response.getheaders()
    

    【讨论】:

      【解决方案2】:

      这很好用:

      import urllib2
      request = urllib2.Request('http://localhost:8080')
      request.get_method = lambda : 'HEAD'
      
      response = urllib2.urlopen(request)
      print response.info()
      

      使用在 python 中被黑客入侵的快速而肮脏的 HTTPd 进行测试:

      Server: BaseHTTP/0.3 Python/2.6.6
      Date: Sun, 12 Dec 2010 11:52:33 GMT
      Content-type: text/html
      X-REQUEST_METHOD: HEAD
      

      我添加了一个自定义标题字段 X-REQUEST_METHOD 以显示它有效:)

      这里是 HTTPd 日志:

      Sun Dec 12 12:52:28 2010 Server Starts - localhost:8080
      localhost.localdomain - - [12/Dec/2010 12:52:33] "HEAD / HTTP/1.1" 200 -
      

      编辑:还有httplib2

      import httplib2
      h = httplib2.Http()
      resp = h.request("http://www.google.com", 'HEAD')
      

      【讨论】:

      • Python3 (3.3+) 添加了对 method 关键字参数的支持到 Request initializer - 作为绕过 lambda 需求的替代方法
      【解决方案3】:

      问题在于您的 HeadRequest 类,它继承自 urllib2.Request。根据文档,urllib2.Request.__init__ 签名是

       __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False) 
      

      所以你必须传递一个 url 参数给它。在您的第二次尝试中,您只是不使用 HeadRequest,这就是它起作用的原因。

      【讨论】:

        【解决方案4】:

        试试 httplib

        >>> import httplib
        >>> conn = httplib.HTTPConnection("www.google.com")
        >>> conn.request("HEAD", "/index.html")
        >>> res = conn.getresponse()
        >>> print res.status, res.reason
        200 OK
        >>> print res.getheaders()
        [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
        

        How do you send a HEAD HTTP request in Python 2?

        【讨论】:

        • 这是否允许您设置其他请求对象?请参阅我的 OP,MyHTTPRedirectHandler
        • 我们在使用这种方法时遇到了一个错误。后来有人想检查一个HTTPS url,你必须使用不同的方法:httplib.HTTPSConnection()
        猜你喜欢
        • 2019-10-20
        • 1970-01-01
        • 2010-09-11
        • 2015-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多