Python 3.x 如何让请求继续尝试连接到url,而不管它在列表中的什么位置出现异常?
我有一个ID列表,我正在传递到for循环中的URL中:Python 3.x 如何让请求继续尝试连接到url,而不管它在列表中的什么位置出现异常?,python-3.x,python-requests,api-design,Python 3.x,Python Requests,Api Design,我有一个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(L)连
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(L
)连接到URL,我该如何做
我根据这个答案设置了这个try/catch()
但是,这会迫使系统退出
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)
这很漂亮,非常感谢,但是它是如何继续尝试重新连接的呢?它使用无限的
while
循环进行重新连接,该循环仅在请求时中断。get
不会引发异常。如果引发异常,则它将打印该异常并进入while
循环的下一次迭代,该循环将再次发出请求。