2010-12-12 20 views
23

Sto cercando di fare una richiesta HEAD di una pagina utilizzando Python 2.Fare richiesta HEAD HTTP con urllib2 da Python 2

sto cercando

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

con misc_urllib2.py contenente

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 

Ma io sono sempre

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

Se io faccio solo

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

allora funziona bene

risposta

57

Questo funziona bene:

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

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

Testato con HTTPd veloce e sporco hacked in pitone:

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 

Ho aggiunto un campo di intestazione personalizzato X-REQUEST_METHOD per vederlo funziona :)

Ecco registro 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 - 

Edit: c'è anche httplib2

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

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

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

+0

fa che consentono di impostare altri objs richiesta? Vedi il mio OP, MyHTTPRedirectHandler – Wizzard

+1

Abbiamo riscontrato un errore utilizzando questo approccio. Successivamente qualcuno ha voluto verificare un URL HTTPS, per il quale è necessario utilizzare un metodo diverso: 'httplib.HTTConnection()' – ericzundel

0

Le bugie problema con la tua classe HeadRequest, che eredita da urllib2.Request. Secondo doc, urllib2.Request.__init__ firma è

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

quindi è necessario passare un argomento URL ad esso. Nel tuo secondo tentativo, non usi HeadRequest, è per questo che funziona.

0

non shoud aggiungere HeadRequest-build_opener o add_handler dovrebbe essere chiamato come questo

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