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