반응형
Python에서 urllib을 사용하여 웹 사이트가 404 또는 200인지 여부를 확인하십시오.
urllib을 통해 헤더 코드를 얻는 방법은 무엇입니까?
getcode () 메서드 (python2.6에 추가됨)는 응답과 함께 전송 된 HTTP 상태 코드를 반환하거나 URL이 HTTP URL이 아닌 경우 없음을 반환합니다.
>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
urllib2 도 사용할 수 있습니다 :
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()
주의 서브 클래스 HTTP 상태 코드를 저장한다.HTTPError
URLError
확실한 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')
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
반응형
'IT' 카테고리의 다른 글
TypeScript에서 여러 유형으로 배열 정의 (0) | 2020.07.25 |
---|---|
angular2 tslint 경고를 중지하기 위해 구성 요소의 기본 접두사를 변경하는 방법 (0) | 2020.07.25 |
NOW () -1 일부터 레코드 선택 (0) | 2020.07.25 |
Haskell에는 가비지 수집기가 필요하고 있습니까? (0) | 2020.07.25 |
부모 활동에서 Fragment 메소드 호출 (0) | 2020.07.25 |