catch specific HTTP error in python

不打扰是莪最后的温柔 提交于 2019-11-27 17:40:57
Tim Pietzcker

Just catch urllib2.HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

So you could do:

import urllib2
try:
   urllib2.urlopen("some url")
except urllib2.HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

For Python 3.x

import urllib.request
try:
    urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
    print(err.code)
sonavolob

Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):

AttributeError: 'URLError' object has no attribute 'code'

Fast, but maybe not the best solution would be code using nested try/except block:

import urllib2
try:
    urllib2.urlopen("some url")
except urllib2.HTTPError, err:
    try:
        if err.code == 404:
            # Handle the error
        else:
            raise
    except:
        ...

More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!