gpt4 book ai didi

python - 从 Python 2 使用 urllib2 发出 HTTP HEAD 请求

转载 作者:IT老高 更新时间:2023-10-28 20:24:19 25 4
gpt4 key购买 nike

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

然后就可以正常使用了

最佳答案

这很好用:

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

关于python - 从 Python 2 使用 urllib2 发出 HTTP HEAD 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4421170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com