我正在尝试创建一个应用程序,让你搜索一家公司的股票缩写,并返回所有必要的数据在Tkinter。我发现了一个很好的API,但当从API获取数据,它返回一个KeyError。请帮助调试这个。
我的代码:
import http.client as client
from tkinter import *
import json
root = Tk()
root.geometry('500x500')
conn = client.HTTPSConnection("realstonks.p.rapidapi.com")
headers = {
'X-RapidAPI-Key': "6ce88770d0mshaf38a1d3b2c09b4p1a3d14jsn3c3ba4f28d50",
'X-RapidAPI-Host': "realstonks.p.rapidapi.com"
}
inputbox = Text(root, padx = 40, pady = 30).pack()
name = ""
def search_function():
name = inputbox.get("1.0","end-1c")
search = Button(root, text = "Search Info", background = "gray", command = search_function)
conn.request("GET", "/" + name.upper(), headers=headers)
res = conn.getresponse()
data = res.read()
data_obj = json.loads(data.decode('utf-8'))
vol = data_obj['total_vol']
price = data_obj['price']
percent = data_obj['change_percentage']
if percent < 0:
fg = 'red'
elif percent > 0:
fg = 'green'
elif percent == 0:
fg = 'gray'
title_widget = Label(root, text = name, font = ("arial bold", 50), underline = True).pack()
vol_widget = Label(root, text = vol + " in total.", font = ("arial bold", 40)).pack()
price_widget = Label(root, text = str(price) + " dollars per share.", font = ("arial bold", 30)).pack()
percent_widget = Label(root, text = str(percent) + "%", font = ("arial bold", 20), fg = fg).pack()
root.mainloop()
错误
Traceback (most recent call last):
File "main.py", line 24, in <module>
vol = data_obj['total_vol']
KeyError: 'total_vol'
1条答案
按热度按时间tf7tbtn21#
在解决问题后,请注意更改api。
要保留需要转换为json的值,所以: