Checking if a website is up via Python

后端 未结 14 1997
南笙
南笙 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:28
    import httplib
    import socket
    import re
    
    def is_website_online(host):
        """ This function checks to see if a host name has a DNS entry by checking
            for socket info. If the website gets something in return, 
            we know it's available to DNS.
        """
        try:
            socket.gethostbyname(host)
        except socket.gaierror:
            return False
        else:
            return True
    
    
    def is_page_available(host, path="/"):
        """ This function retreives the status code of a website by requesting
            HEAD data from the host. This means that it only requests the headers.
            If the host cannot be reached or something else goes wrong, it returns
            False.
        """
        try:
            conn = httplib.HTTPConnection(host)
            conn.request("HEAD", path)
            if re.match("^[23]\d\d$", str(conn.getresponse().status)):
                return True
        except StandardError:
            return None
    
    0 讨论(0)
  • 2020-12-04 10:31

    The HTTPConnection object from the httplib module in the standard library will probably do the trick for you. BTW, if you start doing anything advanced with HTTP in Python, be sure to check out httplib2; it's a great library.

    0 讨论(0)
提交回复
热议问题