使用Python 2的urllib2发起HTTP HEAD请求

23 投票
4 回答
18511 浏览
提问于 2025-04-16 08:25

我正在尝试用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())

那就没问题了

4 个回答

0

问题出在你的 HeadRequest 类上,它是从 urllib2.Request 这个类继承来的。根据文档,urllib2.Request.__init__ 的定义是这样的:

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

所以你必须给它传一个 url 参数。在你第二次尝试的时候,你根本没有使用 HeadRequest 类,这就是为什么它能正常工作的原因。

1

试试 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')]

查看 如何在 Python 2 中发送 HEAD HTTP 请求?

59

这个方法运行得很好:

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

response = urllib2.urlopen(request)
print response.info()

我用Python快速搭建了一个简单的HTTP服务器来测试:

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来证明它有效 :)

这是HTTP服务器的日志:

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

撰写回答