2009-11-13 9 views

cevap

152

getcode() yöntemi (python2.6'da eklendi), yanıtla birlikte gönderilen HTTP durum kodunu veya URL URL URL'si yoksa Hiçbiri değerini döndürür.

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

Not bu getCode() Python 2.6 ilave edildi. – Mark

+1

@Mark, iyi nokta –

+2

Bazı 2.6 öncesi sürümlerinde, a.code çalışır. – user183037

80

Siz de urllib2 kullanabilirsiniz: HTTPError HTTP durum kodunu depolayan URLError bir alt sınıfıdır

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

Not söyledi. Python 3 için

+0

İkincisi "hata" mı? –

+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, http istek kodu (200, 404, 500, vb.), Urllib2 tarafından atılan genel bir hatadan kaçınmakla ilgilenir. –

14

:

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

[URLError] için (https://docs.python.org/3.5/library/urllib.error.html) 'print (e.reason)' kullanılabilir. – Liliane