开发者

Python urllib2 multiple try statement on urlopen()

开发者 https://www.devze.com 2023-01-01 08:30 出处:网络
So, simply I want to be able to run a for across a list of URLs, if one fails then I want 开发者_如何学Pythonto continue on to try the next.

So, simply I want to be able to run a for across a list of URLs, if one fails then I want 开发者_如何学Pythonto continue on to try the next.

I've tried using the following but sadly it throws and exception if the first URL doesn't work.

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).

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


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.

User error.

0

精彩评论

暂无评论...
验证码 换一张
取 消