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

后端 未结 7 887
有刺的猬
有刺的猬 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 02:52

    Addressing @Niklas R's comment to @nickanor's answer:

    from urllib.error import HTTPError
    import urllib.request
    
    def getResponseCode(url):
        try:
            conn = urllib.request.urlopen(url)
            return conn.getcode()
        except HTTPError as e:
            return e.code
    

提交回复
热议问题