Catching http errors

假如想象 提交于 2019-12-01 16:16:42
import urllib2 
try:
   page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
   if err.code == 404:
       print "Page not found!"
   elif err.code == 403:
       print "Access denied!"
   else:
       print "Something happened! Error code", err.code
except urllib2.URLError, err:
    print "Some other error happened:", err.reason

In your case, the error happens already before the HTTP connection could be built - therefore you need to add another error handler that catches URLError. But this has nothing to do with 404 or 403 errors.

0xAX
req = urllib2.Request('url')
>>> try:
>>>     urllib2.urlopen(req)
>>> except urllib2.URLError, e:
>>>     print e.code
>>>     print e.read()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!