What’s the best way to get an HTTP response code from a URL?

后端 未结 7 875
有刺的猬
有刺的猬 2020-11-28 02:34

I’m looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). I’m not sure which library to use.

7条回答
  •  自闭症患者
    2020-11-28 03:02

    Here's a solution that uses httplib instead.

    import httplib
    
    def get_status_code(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
            None instead.
        """
        try:
            conn = httplib.HTTPConnection(host)
            conn.request("HEAD", path)
            return conn.getresponse().status
        except StandardError:
            return None
    
    
    print get_status_code("stackoverflow.com") # prints 200
    print get_status_code("stackoverflow.com", "/nonexistant") # prints 404
    

提交回复
热议问题