问题:我有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

关于python - 如何检查两个以上URL的HTTP错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39756947/

10-13 08:31