问题:我有 3 个 URL - testurl1、testurl2 和 testurl3。我想先尝试 testurl1,如果出现 404 错误,则尝试 testurl2,如果出现 404 错误,则尝试 testurl3。如何做到这一点?到目前为止,我已经在下面尝试过,但这只适用于两个 url,如何添加对第三个 url 的支持?
from urllib2 import Request, urlopen
from urllib2 import URLError, HTTPError
def checkfiles():
req = Request('http://testurl1')
try:
response = urlopen(req)
url1=('http://testurl1')
except HTTPError, URLError:
url1 = ('http://testurl2')
print url1
finalURL='wget '+url1+'/testfile.tgz'
print finalURL
checkfiles()
请您参考如下方法:
普通旧 for 循环的另一个工作:
for url in testurl1, testurl2, testurl3
req = Request(url)
try:
response = urlopen(req)
except HttpError as err:
if err.code == 404:
continue
raise
else:
# do what you want with successful response here (or outside the loop)
break
else:
# They ALL errored out with HTTPError code 404. Handle this?
raise err
