Python check if website exists

后端 未结 8 1917
甜味超标
甜味超标 2020-11-27 12:51

I wanted to check if a certain website exists, this is what I\'m doing:

user_agent = \'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)\'
headers = { \'User         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 13:15

    from urllib2 import Request, urlopen, HTTPError, URLError
    
    user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
    headers = { 'User-Agent':user_agent }
    link = "http://www.abc.com/"
    req = Request(link, headers = headers)
    try:
            page_open = urlopen(req)
    except HTTPError, e:
            print e.code
    except URLError, e:
            print e.reason
    else:
            print 'ok'
    

    To answer the comment of unutbu:

    Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source

提交回复
热议问题