Checking if a website is up via Python

后端 未结 14 2046
南笙
南笙 2020-12-04 09:27

By using python, how can I check if a website is up? From what I read, I need to check the "HTTP HEAD" and see status code "200 OK", but how to do so ?

14条回答
  •  既然无缘
    2020-12-04 10:23

    from urllib.request import Request, urlopen
    from urllib.error import URLError, HTTPError
    req = Request("http://stackoverflow.com")
    try:
        response = urlopen(req)
    except HTTPError as e:
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
    except URLError as e:
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    else:
        print ('Website is working fine')
    

    Works on Python 3

提交回复
热议问题