使用Python 2中的urllib2发出HTTP HEAD请求

23

我正在尝试使用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个回答

59
这很好地起作用:
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')

1
Python3(3.3+)为Request初始化程序添加了对method关键字参数的支持,作为绕过需要使用lambda的替代方法。 - nerdwaller

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请求?


这是否允许您设置其他请求对象?请参阅我的 OP,MyHTTPRedirectHandler。 - Wizzard
1
我们在使用这种方法时遇到了一个错误。后来有人想要检查一个HTTPS URL,对于这种情况,你必须使用不同的方法:httplib.HTTPSConnection() - ericzundel

0

你不应该将HeadRequest添加到build_openeradd_handler中,而应该像这样调用它

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

0
问题出在你的 HeadRequest 类上,它继承了 urllib2.Request。根据文档,urllib2.Request.__init__ 的函数签名是:
 __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False) 

所以你必须向它传递一个url参数。在你的第二次尝试中,你只是没有使用HeadRequest,这就是为什么它能够工作的原因。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接