본문 바로가기
파이썬

파이썬 웹 사이트가 있는지 Python 확인

by º기록 2021. 1. 16.
반응형

특정 웹 사이트가 있는지 확인하고 싶었습니다. 이것이 제가하는 일입니다.

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

 

 

반응형

댓글