Python urllib2 URLError HTTP状态代码。 [英] Python urllib2 URLError HTTP status code.
问题描述
一旦出现URLError异常,我想获取HTTP状态代码:
I want to grab the HTTP status code once it raises a URLError exception:
我尝试了此操作但没有帮助:
I tried this but didn't help:
except URLError, e:
logger.warning( 'It seems like the server is down. Code:' + str(e.code) )
推荐答案
在捕获到 URLError
,因为在没有可用的HTTP状态代码的情况下(例如,当您遇到连接被拒绝的错误时),会引发该异常。
You shouldn't check for a status code after catching URLError
, since that exception can be raised in situations where there's no HTTP status code available, for example when you're getting connection refused errors.
使用 HTTPError
检查特定于HTTP的错误,然后使用 URLError
检查其他问题:
Use HTTPError
to check for HTTP specific errors, and then use URLError
to check for other problems:
try:
urllib2.urlopen(url)
except urllib2.HTTPError, e:
print e.code
except urllib2.URLError, e:
print e.args
当然,您可能会想做一些比仅打印错误代码更聪明的事情,但是您可以等等。
Of course, you'll probably want to do something more clever than just printing the error codes, but you get the idea.
这篇关于Python urllib2 URLError HTTP状态代码。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!