Python urllib2 HTTPError异常没有给出所需的输出

时间:2015-12-28 01:11:51

标签: python exception-handling urllib2 http-error

我正在使用urllib2来获取内容为一行号的页面,然后将该数字与ver值进行比较。这是我的代码片段:

import urllib2

ver = '1.1'
p = urllib2.urlopen('http://www.someurl.com/text')
try:
    p
    for line in p:
        if line == ver:
            print "Current version:  %s" % ver
            print "Latest version:   %s" % line
            print "It's up to date."
        else:
            print "Current version:  %s" % ver
            print "Latest version:   %s" % line
            print "Needs updating."
except urllib2.URLError:
    print "Error, could not retrieve version number!"
except urllib2.HTTPError:
    print "Error, could not retrieve version number!"

我更改了几次网址,看看输出会如何变化。我添加了URLError异常作为对根本无法连接到页面的响应,并且它工作正常。输出为Error, could not retrieve version number!

但是,将p更改为返回HTTP 404错误的某个网址时,添加HTTPError例外无效。这是输出:

Traceback (most recent call last):
 File "/usr/local/bin/script", line 1337, in <module>
  p = urllib2.urlopen('http://www.someurl.com/text')
 File "/.../urllib2.py", line 127, in urlopen
  return _opener.open(url, data, timeout)
 ...
 similar error lines
 ...
urllib2.HTTPError: HTTP Error 404: Not Found

我怎样才能让HTTPError工作?我觉得奇怪的是,一个例外有效,另一个没有,除非我做错了。

1 个答案:

答案 0 :(得分:0)

好吧所以我解决了我的问题。正如Peter Wood在评论中指出的那样,问题是我的网址位于try/except区块的外部,所以我所要做的就是忘记p而只是去做这样:

try:
    for line in urllib2.urlopen('http://www.someurl.com/text'):
        if line == ver:
            #...

现在输出为Error, could not retrieve version number!正如预期的那样。

相关问题