如何检查两个以上的URL的HTTP错误?

时间:2016-09-28 20:21:28

标签: python http-error

问题:我有3个URL - testurl1,testurl2和testurl3。我想首先尝试testurl1,如果我得到404错误然后尝试testurl2,如果得到404错误然后尝试testurl3。怎么做到这一点?到目前为止,我已尝试过以下但仅适用于两个网址,如何添加对第三个网址的支持?

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

2 个答案:

答案 0 :(得分:2)

普通老式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

答案 1 :(得分:0)

嗯,也许是这样的?

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:
        try:
            url1 = ('http://testurl2')
        except HTTPError, URLError:
            url1 = ('http://testurl3')
    print url1
    finalURL='wget '+url1+'/testfile.tgz'

    print finalURL

checkfiles()