2009-11-13 12 views

Respuesta

152

El método getcode() (Agregado en python2.6) devuelve el código de estado HTTP que se envió con la respuesta, o None si la URL no es una URL HTTP.

>>> a=urllib.urlopen('http://www.google.com/asdfsf') 
>>> a.getcode() 
404 
>>> a=urllib.urlopen('http://www.google.com/') 
>>> a.getcode() 
200 
+14

Nota que getCode se añadió() en Python 2.6. – Mark

+1

@Mark, buen punto –

+2

En algunas versiones anteriores a la 2.6, a.code funciona. – user183037

80

Puede utilizar urllib2 así:

import urllib2 

req = urllib2.Request('http://www.python.org/fish.html') 
try: 
    resp = urllib2.urlopen(req) 
except urllib2.HTTPError as e: 
    if e.code == 404: 
     # do something... 
    else: 
     # ... 
except urllib2.URLError as e: 
    # Not an HTTP-specific error (e.g. connection refused) 
    # ... 
else: 
    # 200 
    body = resp.read() 

Tenga en cuenta que HTTPError es una subclase de URLError que almacena el código de estado HTTP.

+0

¿Es el segundo 'else' un error? –

+4

Nope: http://stackoverflow.com/questions/855759/python-try-else –

6
import urllib2 

try: 
    fileHandle = urllib2.urlopen('http://www.python.org/fish.html') 
    data = fileHandle.read() 
    fileHandle.close() 
except urllib2.URLError, e: 
    print 'you got an error with the code', e 
+5

TIMEX está interesado en obtener el código de solicitud http (200, 404, 500, etc.), no es un error genérico lanzado por urllib2. –

14

Para Python 3:

import urllib.request, urllib.error 

url = 'http://www.google.com/asdfsf' 
try: 
    conn = urllib.request.urlopen(url) 
except urllib.error.HTTPError as e: 
    # Return code error (e.g. 404, 501, ...) 
    # ... 
    print('HTTPError: {}'.format(e.code)) 
except urllib.error.URLError as e: 
    # Not an HTTP-specific error (e.g. connection refused) 
    # ... 
    print('URLError: {}'.format(e.reason)) 
else: 
    # 200 
    # ... 
    print('good') 
+0

Para [URLError] (https://docs.python.org/3.5/library/urllib.error.html) 'print (e.reason)' podría ser utilizado. – Liliane

Cuestiones relacionadas