【问题标题】:Itereting over an API with Json,使用 Json 迭代 API,
【发布时间】:2020-06-28 18:52:23
【问题描述】:

导入请求 导入json 将 numpy 导入为 np 将熊猫导入为 pd

url = "https://financialmodelingprep.com/api/v3/financial-statement-growth/PETS" JC = requests.get(url).json()

content = json.dumps(JC, indent = 4, sort_keys=True)

日期 = ["PETS", "APPL"]

dates_list =[]

对于日期中的日期: JC = requests.get("https://financialmodelingprep.com/api/v3/financial-statement-growth/"+ 日期).json()

dates_list.append(JC['growth'])

数据集 = pd.DataFrame(dates_list) dataset.sample(5)

我得到这个错误:

KeyError Traceback(最近一次调用最后一次) 在 6 JC = requests.get("https://financialmodelingprep.com/api/v3/financial-statement-growth/"+ 日期).json() 7 ----> 8 dates_list.append(JC['growth']) 9 10 数据集 = pd.DataFrame(dates_list)

KeyError: '成长'

【问题讨论】:

    标签: python json pandas


    【解决方案1】:
    import requests 
    import json 
    import numpy as np 
    import pandas as pd
    
    url = "https://financialmodelingprep.com/api/v3/financial-statement-growth/PETS" 
    JC = requests.get(url).json()
    
    content = json.dumps(JC, indent = 4, sort_keys=True)
    
    dates = ["PETS", "AAPL", "APPL"]
    
    dates_list =[]
    
    for dates in dates: 
    
        JC = requests.get("https://financialmodelingprep.com/api/v3/financial-statement-growth/"+ dates).json()
        if JC == {}:
            print "invalid ticker ... "
        else:
            dates_list.append(JC['growth'])
    
    
    dataset = pd.DataFrame(dates_list)
    print dataset
    
    

    首先股票代码APPL在SEC数据库中不存在https://www.sec.gov/cgi-bin/browse-edgar?CIK=APPL&owner=exclude&action=getcompany 然后api返回一个空目录,其中没有出现密钥增长。您应该捕获错误,您可以在将值添加到 dates_lists 之前检查字典是否为空

    控制台输出

    fmp_team:fmp $ python stackoverflow.py 
    invalid ticker ... 
                                                      0                                                  1   ...                                                 9                                                  10
    0  {u'Weighted Average Shares Diluted Growth': u'...  {u'Weighted Average Shares Diluted Growth': u'...  ...  {u'Weighted Average Shares Diluted Growth': u'...                                               None
    1  {u'Weighted Average Shares Diluted Growth': u'...  {u'Weighted Average Shares Diluted Growth': u'...  ...  {u'Weighted Average Shares Diluted Growth': u'...  {u'Weighted Average Shares Diluted Growth': u'...
    
    [2 rows x 11 columns]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2019-01-23
      • 2020-12-04
      • 2017-07-05
      • 2013-07-30
      • 2019-05-12
      相关资源
      最近更新 更多