2009-11-13 1 views

답변

152

getcode() 메소드 (python2.6에 추가됨)는 응답과 함께 전송 된 HTTP 상태 코드를 반환하거나 URL이 HTTP URL이 아닌 경우 None을 반환합니다.

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

참고 getcode()는 2.6 파이썬 첨가 하였다. – Mark

+1

@Mark, 좋은 지적 –

+2

일부 2.6 이전 버전에서는 a.code가 작동합니다. – user183037

80

당신은뿐만 아니라 urllib2를 사용할 수 있습니다 HTTPError이 HTTP 상태 코드를 저장 URLError의 서브 클래스가

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

하는 것으로. 파이썬 3

+0

두 번째'else'는 실수입니까? –

+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는 urllib2에서 발생하는 일반 오류가 아닌 HTTP 요청 코드 (200, 404, 500 등)를 가져 오는 데 관심이 있습니다. –

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] (https://docs.python.org/3.5/library/urllib.error.html)의 경우'print (e.reason)'를 사용할 수 있습니다. – Liliane