[英]Python urllib2 multiple try statement on urlopen()
So, simply I want to be able to run a for across a list of URLs, if one fails then I want to continue on to try the next. 因此,我只是希望能够在一系列URL上运行for,如果一个URL失败,那么我想继续尝试下一个。
I've tried using the following but sadly it throws and exception if the first URL doesn't work. 我尝试使用以下内容,但遗憾的是,如果第一个URL不起作用,则会引发异常。
servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
try:
u = urllib2.urlopen(server)
except urllib2.URLError:
continue
else:
break
else:
raise
Any ideas? 有任何想法吗?
Thanks in advance. 提前致谢。
servers = ('http://www.google.com', 'http://www.stackoverflow.com')
for server in servers:
try:
u = urllib2.urlopen(server)
except urllib2.URLError:
continue
else:
break
else:
raise
This code breaks out of the loop if the url connection doesn't raise an error ( else: break
part). 如果url连接未引发错误,则此代码会中断循环(
else: break
部分)。
Do you want the 2nd one used only if the first fails? 您是否要仅在第一个失败的情况下使用第二个?
edit: I thought that the else:
following the for loop should raise
because of the break
, but in my quick test that didn't work ... because my understanding of for/else was wrong 编辑:我认为
else:
下面的for循环应该raise
,因为的break
,但在我的快速测试,没有工作......因为我的理解对/别人是错的
So the problem turned out to be user error. 因此问题出在用户错误上。 I was trying stupid domains like "wegwegwe.com" but I never actually had a usable domain in the list, so eventually it did just raise the exception.
我尝试使用“ wegwegwe.com”之类的愚蠢域名,但实际上我从未在列表中拥有可用域名,因此最终它确实引发了异常。
User error. 用户错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.