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

后端 未结 7 844
有刺的猬
有刺的猬 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:08

    You should use urllib2, like this:

    import urllib2
    for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
        try:
            connection = urllib2.urlopen(url)
            print connection.getcode()
            connection.close()
        except urllib2.HTTPError, e:
            print e.getcode()
    
    # Prints:
    # 200 [from the try block]
    # 404 [from the except block]
    
    0 讨论(0)
提交回复
热议问题