如何让请求继续尝试连接到url,无论它从列表中的哪个位置出现异常?

问题描述 投票:1回答:1

我有一个ID列表,我将其传递到for循环中的URL:

L = [1,2,3]
lst=[]
for i in L:
    url = 'URL.Id={}'.format(i)
    xml_data1 = requests.get(url).text
    lst.append(xml_data1)
    time.sleep(1)
    print(xml_data1)

我正在尝试创建一个try / catch,无论错误如何,请求库都会继续尝试从列表中保留的ID连接到URL(L),我该怎么做?

我从这个答案设置了这个try / catch(Correct way to try/except using Python requests module?

然而,这迫使系统退出。

try:
    for i in L:
        url = 'URL.Id={}'.format(i)
        xml_data1 = requests.get(url).text
        lst.append(xml_data1)
        time.sleep(1)
        print(xml_data1)
except requests.exceptions.RequestException as e:
    print (e)
    sys.exit(1)
python-3.x python-requests api-design
1个回答
1
投票

你可以把try-except块放在一个循环中,当请求没有引发异常时,只有break循环:

L = [1,2,3]
lst=[]
for i in L:
    url = 'URL.Id={}'.format(i)
    while True:
        try:
            xml_data1 = requests.get(url).text
            break
        except requests.exceptions.RequestException as e:
            print(e)
    lst.append(xml_data1)
    time.sleep(1)
    print(xml_data1)
© www.soinside.com 2019 - 2024. All rights reserved.