Python:urlopen-如果发生任何错误,则跳过条目
我想知道,如果访问网站时出现任何错误,urlopen是否有某种“一网打尽”的代码会跳过我的for循环中的整个条目。您可以通过Python:urlopen-如果发生任何错误,则跳过条目,python,urllib2,urlopen,Python,Urllib2,Urlopen,我想知道,如果访问网站时出现任何错误,urlopen是否有某种“一网打尽”的代码会跳过我的for循环中的整个条目。您可以通过try/except块捕获异常: # Python 3 example from urllib.error import URLError, HTTPError from urllib.request import urlopen for entry in entries: try: data = urlopen(...) except
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
使用
try
和除了代码“有效”,因为我在运行它时没有收到任何错误,但我不确定它是否有效,因为它可能会跳过出现的任何问题,或者根本没有任何错误,因此没有代码的“激活”。如果您想查看它是否执行,可以尝试在else
块中添加一些打印
。@user3476845:要忽略所有错误,请捕获异常
对象。urleror和HTTPError是不够的。