python-3.x - 如何让请求继续尝试连接到 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)
解决方案
您可以将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)
推荐阅读
- python - 将多个数据集的 csv 文件组织成 Pandas 数据框列表
- php - PHP插件逻辑不适用
- java - 将 MultiDex 添加到 android studio 中的项目但不断收到 java.lang.NoClassDefFoundError
- c# - 如何在 Entity Framework 6 Database First 中对导航属性实现乐观并发
- html - 带有 SVG 的任务时间线 - 无法为最终过渡设置动画
- machine-learning - 使用交叉验证的多性能指标
- javascript - 如何使 mat-select 第一个选项为空?
- oop - 单一职责原则:一个问题
- git - 使用--allow-unrelated-history 维护历史?
- c - 如何将字符串与字符串数组进行比较?