python - 使用 Json 迭代 API,
问题描述
导入请求导入 json 导入 numpy 作为 np 导入 pandas 作为 pd
url = " https://financialmodelingprep.com/api/v3/financial-statement-growth/PETS " JC = requests.get(url).json()
内容 = json.dumps(JC, 缩进 = 4, sort_keys=True)
日期 = [“宠物”,“APPL”]
日期列表 =[]
对于日期中的日期:JC = requests.get(" https://financialmodelingprep.com/api/v3/financial-statement-growth/ "+ dates).json()
dates_list.append(JC['growth'])
dataset = pd.DataFrame(dates_list) dataset.sample(5)
我得到这个错误:
6 JC = requests.get(" https://financialmodelingprep.com/api/v3/financial-statement-growth/ "+ dates).json() 7 ----> 8中的 KeyError Traceback(最近一次通话最后一次)dates_list.append(JC['growth']) 9 10 数据集 = pd.DataFrame(dates_list)
KeyError:“增长”
解决方案
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]
推荐阅读
- google-apps-script - 尝试在工作表上复制列范围并将其粘贴到不同工作表上的一行中,并在每次脚本运行时将其插入顶部
- python - Apache Beam I/O 转换
- swift - 如何在 Xcode 中创建环绕式代码片段
- javascript - 使用 PDFBox 2.x 在 PDF 上放置一个按钮
- python - 如果不为空,则将参数传递给方法
- c# - C# ConcurrentDictionary 条件添加
- python - 加入两个 modin.pandas.DataFrame(s)
- python - 如何/我可以从 Python 中的 Twitter 帐户中检索文本数据
- numpy - 创建一个绿色通道比蓝色和红色更亮的蒙版?
- c++ - 编译错误“错误:预期的';' 在声明列表末尾”使用 C++ 中的 Catch 测试框架