如何使请求继续尝试连接到 url 而不管它在列表中停止的位置有异常?

How to make requests keep trying to connect to url regardless of exception from where it left off in the list?

我有一个 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)

您可以将 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)