首页 > 解决方案 > 如何让请求继续尝试连接到 url,而不管它在列表中从哪里中断?

问题描述

我有一个 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,无论错误如何,请求库都会不断尝试从列表 ( L) 中留下的 ID 连接到 URL,我该怎么做?

我从这个答案中设置了这个try/catch(正确的尝试方式/使用Python请求模块除外?

但是,这会强制系统退出。

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.xpython-requestsapi-design

解决方案


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

推荐阅读