捕获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>
2 个回答
5
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如说,有人可能在使用某个库时,发现它的某些功能没有按预期工作。这种情况可能会让人感到困惑,不知道该怎么解决。
通常,解决这类问题的第一步是查看文档。文档就像是使用说明书,里面会详细介绍这个工具或库的用法和注意事项。如果文档中没有找到答案,接下来可以考虑在网上搜索一下,看看其他人是否遇到过类似的问题。
另外,参与社区讨论也是一个好办法。在像StackOverflow这样的论坛上,很多开发者会分享他们的经验和解决方案。你可以把你的问题发上去,看看有没有人能给你提供帮助。
总之,遇到问题时不要慌张,先查文档,再搜索一下,最后可以向社区求助。这样一步一步来,通常都能找到解决办法。
req = urllib2.Request('url')
>>> try:
>>> urllib2.urlopen(req)
>>> except urllib2.URLError, e:
>>> print e.code
>>> print e.read()
23
import urllib2
try:
page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
if err.code == 404:
print "Page not found!"
elif err.code == 403:
print "Access denied!"
else:
print "Something happened! Error code", err.code
except urllib2.URLError, err:
print "Some other error happened:", err.reason
在你的情况下,错误发生在HTTP连接建立之前,所以你需要添加一个新的错误处理程序来捕捉URLError
。不过,这个错误和404或403错误没有关系。