问题描述
我正在尝试制作货币转换器,但出现此错误,原因是什么?
我正在使用 alphavantage 来获取值。
import requests,json
def AlPHPaFetcher(from_currency,to_currency,api_key):
alpha_url = r"https://www.alphavantage.co/query?function = CURRENCY_EXCHANGE_RATE"
final_url = alpha_url + "&from_currency =" + from_currency + "&to_currency =" + to_currency + "&apikey =" + api_key
req_ob = requests.get(final_url)
result = req_ob.json()
print("Realtime Currency Exchange Rate for",result["Realtime Currency Exchange Rate"]
["2. From_Currency Name"],"TO",result["Realtime Currency Exchange Rate"]
["4. To_Currency Name"],"is",result["Realtime Currency Exchange Rate"]
['5. Exchange Rate'],to_currency)
if __name__ == "__main__" :
from_currency = "USD"
to_currency = "BRL"
api_key = "XXXXXXXXXX"
AlPHPaFetcher(from_currency,api_key)
并返回这个
Traceback (most recent call last):
File "c:\Users\Lucas\Desktop\teste.py",line 37,in <module>
AlPHPaFetcher(from_currency,api_key)
File "c:\Users\Lucas\Desktop\teste.py",line 19,in AlPHPaFetcher
result["Realtime Currency Exchange Rate"]
KeyError: 'Realtime Currency Exchange Rate'
解决方法
更正您的网址结构:(注意 =
前没有空格)
alpha_url = r"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE"
final_url = alpha_url + "&from_currency=" + from_currency + "&to_currency=" + to_currency + "&apikey=" + api_key
req_ob = requests.get(final_url)