質問

Python 2を使用してページのヘッドリクエストを実行しようとしています。

やっています

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

他のヒント

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でHTTPリクエストをどのように送信しますか?

問題は、urllib2.requestから継承するクラスのヘッドレクエストにあります。 Docによると、 urllib2.Request.__init__ 署名はです

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

したがって、URL引数を渡す必要があります。 2回目の試みでは、HeadRequestを使用しないでください。これが機能する理由です。

追加しないでください HeadRequestbuild_opener また add_handler このように呼ばれるべきです

opener = urllib2.build_opener(MyHTTPRedirectHandler)
response = opener.open(HeadRequest(url))
print response.getheaders()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top