为什么打印时出现AttributeError错误
我正在通过这个教程学习urllib2 http://docs.python.org/howto/urllib2.html#urlerror,运行下面的代码时,结果和教程里不一样。
import urllib2
req = urllib2.Request('http://www.pretend-o-server.org')
try:
urllib2.urlopen(req)
except urllib2.URLError, e:
print e.reason
Python解释器返回了这个结果。
Traceback (most recent call last):
File "urlerror.py", line 8, in <module>
print e.reason
AttributeError: 'HTTPError' object has no attribute 'reason'
为什么会这样呢?
更新
当我尝试打印代码属性时,它工作得很好。
import urllib2
req = urllib2.Request('http://www.pretend-o-server.org')
try:
urllib2.urlopen(req)
except urllib2.URLError, e:
print e.code
3 个回答
4
因为没有这个属性。你可以试试:
print str(e)
这样你就能得到不错的效果:
HTTP Error 404: Not Found
8
根据错误的类型,对象 e
可能会有这个属性,也可能没有。
在你提供的链接中,有一个更完整的例子:
第二个例子
from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
response = urlopen(req)
except URLError, e:
if hasattr(e, 'reason'): # <--
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # <--
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
else:
# everything is fine
1
我遇到AttributeError的原因是因为我在使用OpenDNS。显然,即使你输入一个不存在的网址,OpenDNS也会把它当成是存在的。所以在我换成谷歌的DNS服务器后,得到了预期的结果,结果是:
[Errno -2] Name or service not known
另外,我还应该提到我运行这段代码时得到的错误追踪信息,除了try和except之外的所有内容是:
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request('http://www.pretend_server.com')
urlopen(req)
就是这个
Traceback (most recent call last):
File "urlerror.py", line 5, in <module>
urlopen(req)
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 397, in open
response = meth(req, response)
File "/usr/lib/python2.6/urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.6/urllib2.py", line 435, in error
return self._call_chain(*args)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
有位好心的朋友在IRC #python告诉我这很奇怪,然后问我是不是在用OpenDNS,我回答说是的。于是他们建议我换成谷歌的DNS,我就照做了。