为什么我在尝试打印时遇到AttributeError

时间:2011-09-26 12:10:05

标签: python attributes urllib2 urllib

我正在通过以下教程了解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 个答案:

答案 0 :(得分:8)

根据错误类型,对象e可能包含也可能不包含该属性。

在您提供的链接中有一个更完整的示例:

  

第2名

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 :(得分:4)

因为没有这样的属性。尝试:

print str(e)

你会很高兴:

HTTP Error 404: Not Found

答案 2 :(得分:1)

我得到AttributeError的原因是因为我使用的是OpenDNS。显然,即使您传入虚假URL,OpenDNS也会将其视为存在。因此,在切换到谷歌DNS服务器后,我得到了预期的结果:

[Errno -2] Name or service not known

另外我应该提一下我运行此代码所得到的回溯,除了

之外的所有内容除了try和
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我回答是的。因此他们建议我将其切换到谷歌,我继续这样做。

相关问题