Python urllib2 URLError HTTP 状态代码。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3465704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python urllib2 URLError HTTP status code.
提问by Hellnar
I want to grab the HTTP status code once it raises a URLError exception:
一旦引发 URLError 异常,我想获取 HTTP 状态代码:
I tried this but didn't help:
我试过这个,但没有帮助:
except URLError, e:
logger.warning( 'It seems like the server is down. Code:' + str(e.code) )
采纳答案by P?r Wieslander
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.
您不应该在URLErrorcatch之后检查状态代码,因为在没有可用的 HTTP 状态代码的情况下可能会引发该异常,例如当您收到连接被拒绝的错误时。
Use HTTPErrorto check for HTTP specific errors, and then use URLErrorto check for other problems:
使用HTTPError检查HTTP特定的错误,然后用URLError检查其他问题:
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.
当然,您可能想要做一些比打印错误代码更聪明的事情,但是您明白了。
回答by Manoj Govindan
Not sure why you are getting this error. If you are using urllib2this should help:
不知道为什么你会收到这个错误。如果您正在使用urllib2它应该会有所帮助:
import urllib2
from urllib2 import URLError
try:
urllib2.urlopen(url)
except URLError, e:
print e.code

