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

后端 未结 7 885
有刺的猬
有刺的猬 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]
    

提交回复
热议问题