반응형
특정 웹 사이트가 있는지 확인하고 싶었습니다. 이것이 제가하는 일입니다.
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com"
req = urllib2.Request(link, headers = headers)
page = urllib2.urlopen(req).read() - ERROR 402 generated here!
페이지가 존재하지 않는 경우 (오류 402 또는 기타 오류) page = ...
행에서 내가 읽고있는 페이지가 종료되는지 확인하기 위해 무엇을 할 수 있습니까?
해결 방법
GET 대신 HEAD 요청을 사용할 수 있습니다. 헤더 만 다운로드하고 콘텐츠는 다운로드하지 않습니다. 그런 다음 헤더에서 응답 상태를 확인할 수 있습니다.
import httplib
c = httplib.HTTPConnection('www.example.com')
c.request("HEAD", '')
if c.getresponse().status == 200:
print('web site exists')
또는 urllib2
를 사용할 수 있습니다.
import urllib2
try:
urllib2.urlopen('http://www.example.com/some_page')
except urllib2.HTTPError, e:
print(e.code)
except urllib2.URLError, e:
print(e.args)
또는 요청
을 사용할 수 있습니다.
import requests
request = requests.get('http://www.example.com')
if request.status_code == 200:
print('Web site exists')
else:
print('Web site does not exist')
참조 페이지 https://stackoverflow.com/questions/16778435
반응형
'파이썬' 카테고리의 다른 글
파이썬 How to get a value from a cell of a dataframe? (0) | 2021.01.16 |
---|---|
파이썬은 튜플에 항목을 추가합니다. (0) | 2021.01.16 |
파이썬에서 한 번에 두 개의 목록 값을 반복 (0) | 2021.01.16 |
파이썬 How to set attributes using property decorators? (0) | 2021.01.16 |
파이썬에서 날짜 문자열 형식을 어떻게 검증합니까? (0) | 2021.01.16 |
댓글