如何在 Python 中捕获特定的 HTTP 错误? [英] How do I catch a specific HTTP error in Python?

查看:46
本文介绍了如何在 Python 中捕获特定的 HTTP 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

import urllib2
try:
   urllib2.urlopen("some url")
except urllib2.HTTPError:
   <whatever>

但我最终发现的是任何类型的 HTTP 错误.仅当指定的网页不存在(404?)时才想捕获.

but what I end up is catching any kind of HTTP error. I want to catch only if the specified webpage doesn't exist (404?).

推荐答案

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

只要捕获HTTPError,处理它,如果不是404错误,只需使用raise重新引发异常.

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

请参阅 Python 教程.

例如Pyhton 2 的完整示例

e.g. complete example for Pyhton 2

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

这篇关于如何在 Python 中捕获特定的 HTTP 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆