为什么我在打印你的时候会得到一个属性错误

2024-03-29 14:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

通过遵循本教程http://docs.python.org/howto/urllib2.html#urlerror来学习urllib2,运行下面的代码可以得到与本教程不同的结果

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'

为什么会这样?

更新

当我试图打印出code属性时,它工作得很好

import urllib2

req = urllib2.Request('http://www.pretend-o-server.org')
try:
    urllib2.urlopen(req)
except urllib2.URLError, e:
    print e.code

Tags: orgimporthttpserverrequestwww教程urllib2
3条回答

我得到属性错误的原因是因为我在使用OpenDNS。显然,即使你输入了一个虚假的URL,OpenDNS也会把它当作它存在。因此,在切换到Googles 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,我回答是的。所以他们建议我把它改成谷歌的,我就这么做了。

根据错误类型的不同,对象e可能携带也可能不携带该属性。

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

Number 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

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

print str(e)

你会变得很好:

HTTP Error 404: Not Found

相关问题 更多 >