我正在使用urllib2方法(在for循环中)发出html请求,但有时我会遇到错误或超时,因此我必须在for循环中启动。有谁能告诉我如何修改我的代码,让它一直尝试,直到我们没有得到错误,而不是重新限制for循环?在
import urllib2,re
proxy = "*.*.*.*:8080"
proxies = {"http":"http://%s" % proxy}
headers={'User-agent' : 'Mozilla/5.0'}
//rest of code here
for num,cname in enumerate(match):
r = re.compile('epi/(.*?)/')
m = r.search(cname[0])
episodeId = m.group(1)
url = "http://api.somesite.net/api/data/Episode/"+str(episodeId);
proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=0))
urllib2.install_opener(opener)
req = urllib2.Request(url, None, headers)
try:
html = urllib2.urlopen(req).read()
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
@retry(urllib2.URLError, tries=4, delay=3, backoff=2)
def urlopen_with_retry():
return urllib2.urlopen("http://example.com")
正如我们在评论中所讨论的,您可以使用
try/except
来避免循环时崩溃(我看到在这个建议之后,您已经更改了原来的代码)然后,当使用
urlopen
(请参见documentation)时,可以指定更长的超时(以秒为单位)。在此外,在
for
循环中,您可以添加另一个循环,该循环将尝试检索特定次数的数据,或在urlopen
获得所需内容后立即中断。以下代码基于this answer:对于那些投了反对票的人来说:OP在评论中讨论后改变了他的问题/代码。这个答案是该讨论的后续,所以请考虑上下文。在
相关问题 更多 >
编程相关推荐