Python:urlopen - 如果发生任何错误,请跳过条目

时间:2014-05-17 20:32:02

标签: python urllib2 urlopen

我想知道是否有某种" Catch all"如果在访问网站时出现任何错误,那么会跳过我的for循环中的整个条目的urlopen代码。

1 个答案:

答案 0 :(得分:4)

您可以使用try/except块捕获异常:

# Python 3 example
from urllib.error import URLError, HTTPError
from urllib.request import urlopen

for entry in entries:
    try:
         data = urlopen(...)
    except URLError, HTTPError:
         print("Something bad happened")
    else:
         # Process data get from the URL opened
         # If an exception has been catch, you won't 
         # enter in this else block
相关问题