捕获http错误
例如,如何捕获 python 和 urllib(2) 中页面的 404 和 403 错误?
有没有不需要大型类包装器的快速方法?
添加的信息(堆栈跟踪):
Traceback (most recent call last):
File "test.py", line 3, in <module>
page = urllib2.urlopen("http://localhost:4444")
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 111] Connection refused>
how can I catch the 404 and 403 errors for pages in python and urllib(2), for example?
Are there any fast ways without big class-wrappers?
Added info (stack trace):
Traceback (most recent call last):
File "test.py", line 3, in <module>
page = urllib2.urlopen("http://localhost:4444")
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 111] Connection refused>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的情况下,错误已经在建立 HTTP 连接之前发生 - 因此您需要添加另一个捕获
URLError
的错误处理程序。但这与 404 或 403 错误无关。In your case, the error happens already before the HTTP connection could be built - therefore you need to add another error handler that catches
URLError
. But this has nothing to do with 404 or 403 errors.