捕获python中的特定HTTP错误 [英] catch specific HTTP error in python
问题描述
我想抓住一个特定的http错误而不是整个家庭中的任何一个..
我想要做的是 -
I want to catch a specific http error and not any one of the entire family.. what I was trying to do is --
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError:
<whatever>
但我最终得到的是任何类型的http错误,但我想抓住的只是指定的网页不存在!!可能那是HTTP错误404 ..但我不知道如何指定只捕获错误404并让系统运行其他事件的默认处理程序..建议??
but what I end up is catching any kind of http error, but I want to catch only if the specified webpage doesn't exist!! probably that's HTTP error 404..but I don't know how to specify that catch only error 404 and let the system run the default handler for other events..ny suggestions??
推荐答案
抓住 urllib2.HTTPError
,处理它,如果不是错误404,只需使用提高
以重新引发异常。
Just catch urllib2.HTTPError
, handle it, and if it's not Error 404, simply use raise
to re-raise the exception.
请参阅 Python教程。
所以你可以这样做:
import urllib2
try:
urllib2.urlopen("some url")
except urllib2.HTTPError as err:
if err.code == 404:
<whatever>
else:
raise
这篇关于捕获python中的特定HTTP错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!