首页 > 解决方案 > 跳过python中的异常

问题描述

我有一个新手问题:假设我在 python 中有这个股票清单

import requests

list = ["AMZN","APPL", "BAC"]

try:
    for x in list:
        url ='https://financialmodelingprep.com/api/v3/quote-short/'+x+'?apikey=demo'
        response = requests.request('GET', url)
        result = response.json()
        print(result[0]["price"]) 

except:
    pass

第二个股票代码将引发异常,无论第二个股票代码请求发生什么,我如何让 python 运行第三个股票代码?

标签: pythonpython-3.x

解决方案


使用如下try-except内部for循环

import requests

list = ["AMZN","APPL", "BAC"]


for x in list:
    try:
        url ='https://financialmodelingprep.com/api/v3/quote-short/'+x+'?apikey=demo'
        response = requests.request('GET', url)
        result = response.json()
        print(result[0]["price"]) 

    except:
       pass

推荐阅读