【发布时间】:2013-03-25 19:46:49
【问题描述】:
我是使用异常处理的新手。我正在使用 mechanize 模块来抓取几个网站。我的程序经常失败,因为连接速度慢并且请求超时。我希望能够在每次尝试之间延迟 30 秒后重试网站(例如超时)最多 5 次。
我查看了this stackoverflow 的答案,可以看到我如何处理各种异常。我也看到(虽然它看起来很笨拙)我如何将尝试/异常放在一个while循环中来控制5次尝试......但我不明白如何跳出循环,或者在连接时“继续”成功并且没有抛出异常。
from mechanize import Browser
import time
b = Browser()
tried=0
while tried < 5:
try:
r=b.open('http://www.google.com/foobar')
except (mechanize.HTTPError,mechanize.URLError) as e:
if isinstance(e,mechanize.HTTPError):
print e.code
tried += 1
sleep(30)
if tried > 4:
exit()
else:
print e.reason.args
tried += 1
sleep(30)
if tried > 4:
exit()
print "How can I get to here after the first successful b.open() attempt????"
我希望得到有关 (1) 如何在成功打开时跳出循环,以及 (2) 如何使整个块不那么笨拙/更优雅的建议。
【问题讨论】:
标签: python exception-handling mechanize-python