尝试捕获404错误时,“ HTTPResponse”对象没有属性“ type”

时间:2019-01-02 07:54:09

标签: python-3.x urllib

我有一些代码可以从API中提取不完整的URL,并将其附加到基本URL。我正在尝试将其扩展为测试每个URL,以确保在输出到屏幕之前不会导致404错误。

我查看了有关如何在python3中使用urllib的其他答案,并认为我已正确完成了所有操作,但是,标题出现错误。

testurl是我的请求,resp是我的答复。这是我正在使用的代码:

                testurl=urllib.request.urlopen("http://www.google.com")
                try:
                    resp = urllib.request.urlopen(testurl)
                except urllib.error.HTTPError as e:
                    if e.code == 404:
                        blah = 1
                    else:
                        print("it worked!")

我想念什么?

完整的错误输出:

Traceback (most recent call last):
  File "imgtst.py", line 27, in <module>
    resp = urllib.request.urlopen(testurl)
  File "/usr/local/lib/python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/lib/python3.7/urllib/request.py", line 517, in open
    protocol = req.type
AttributeError: 'HTTPResponse' object has no attribute 'type'

编辑:

在由于布鲁诺的回答指出问题之后,我尝试尝试以下代码:

try:
    resp = urllib.request.urlopen("http://www.google.com")
except urllib.error.HTTPError as e:
    if e.code == 404:
        print("error")
    else:
        print("it worked")

但是,这根本不打印任何内容。

1 个答案:

答案 0 :(得分:0)

这里:

 testurl=urllib.request.urlopen("http://www.google.com")
 try:
    resp = urllib.request.urlopen(testurl)

第一行调用urlopen并将结果(一个HTTPResponse对象)绑定到testurl。然后在try块中,第二次调用urlopen以HTTPResponse对象作为参数-当然是无效的。

编辑:

带有已编辑的代码,即:

try:
    resp = urllib.request.urlopen("http://www.google.com")
except urllib.error.HTTPError as e:
    if e.code == 404:
        print("error")
    else:
        print("it worked")

“有效”仅在引发HTTPError并且不是404时显示-else子句与if e.code == 404相匹配。因此,当然,如果没有错误,则什么都不会打印。

您想要的是:

try:
    result = something_that_may_raise(...)
except SomeExceptionType as e:
    handle_the_error
else:
    do_something_with(result)

因此,在您的情况下,它看起来像:

try:
    response = urllib.request.urlopen("http://www.google.com")
except urllib.error.HTTPError as e:
    print("error code {}".format(e.code))
else:
    print("it worked: {}".format(response))

请注意,此处的else子句与try子句匹配。