2012-01-12 10 views
14

Ho un pezzo di codice come questourllib2 HTTP Error 400: Bad Request

host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (query, page) 
req = urllib2.Request(host) 
req.add_header('User-Agent', User_Agent) 
response = urllib2.urlopen(req) 

e quando ho una query di ingresso maggiore di una parola come "il cane" ottengo il seguente errore.

response = urllib2.urlopen(req) 
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen 
return _opener.open(url, data, timeout) 
File "/usr/lib/python2.7/urllib2.py", line 400, in open 
response = meth(req, response) 
File "/usr/lib/python2.7/urllib2.py", line 513, in http_response 
'http', request, response, code, msg, hdrs) 
File "/usr/lib/python2.7/urllib2.py", line 438, in error 
return self._call_chain(*args) 
File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain 
result = func(*args) 
File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default 
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 400: Bad Request 

Qualcuno può segnalare cosa sta facendo male? Grazie in anticipo.

+0

Ho anche ricevuto "urllib2.HTTPError: HTTP Error 406: Not Acceptable" quando si tenta di richiedere URL con spazi vuoti. – jamesc

risposta

53

Il motivo per cui "il cane" restituisce un errore 400 è perché non si sta eseguendo l'escape della stringa per un URL.

Se si esegue questa operazione:

import urllib, urllib2 

quoted_query = urllib.quote(query) 
host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (quoted_query, page) 
req = urllib2.Request(host) 
req.add_header('User-Agent', User_Agent) 
response = urllib2.urlopen(req) 

Funzionerà.

Tuttavia, suggerisco caldamente di utilizzare requests anziché utilizzare urllib/urllib2/httplib. È molto più semplice e gestirà tutto questo per te.

Questo è lo stesso codice con le richieste di pitone:

import requests 

results = requests.get("http://www.bing.com/search", 
       params={'q': query, 'first': page}, 
       headers={'User-Agent': user_agent}) 
+0

Mi piace il tuo suggerimento! Grazie! –

5

È necessario utilizzare urllib.quote() sulla variabile 'query':

query = urllib.quote(query) 
host = 'http://www.bing.com/search?q=%s&go=&qs=n&sk=&sc=8-13&first=%s' % (query, page) 

Questo fa l'URL necessario fuggire per convertire lo spazio in big dog-big%20dog.

-1

Ho anche incontrato lo stesso problema. Risulta il problema era il metodo è stato impostato in modo inappropriato. Quando si includono i dati urlencoded in urllib2.urlopen(), il metodo deve essere impostato su POST e quando lo si esclude, il metodo deve essere GET. Quindi, come si fa a impostare il metodo è il seguente:

Per richiesta POST

request_object = urllib2.Request(url) 
method = ("POST", "GET") 
request_object.get_method = lambda: method[0] #If method is set to POST 
url_handle = opener.open(req, data) #If method is set to POST 

Per richiesta GET

request_object = urllib2.Request(url) 
method = ("POST", "GET") 
request_object.get_method = lambda: method[1] #If method is set to GET 
url_handle = opener.open(req) #If method is set to GET 

Questo imposterà il vostro metodo di richiesta URL per il metodo richiesto appropriata

Problemi correlati