所以,这是脚本。我正在使用我在互联网上找到的这个api,它可以工作,但当我试图让它只打印我想要的信息时,显示了以下错误:
Traceback (most recent call last):
File "c:/Users/perei/OneDrive/Documentos/Evylla/python/projetos python/cotacao_dolar.py", line 13, in <module>
print("Moeda estrangeira: {}".format(dolar_cot["code"]))
KeyError: 'code'import requests
import json
dolar = requests.get("https://economia.awesomeapi.com.br/all/USD-BRL")
dolar_cot = dolar.json()
# print(dolar.text)
if "status" == 404:
print("Moeda não encontrada")
else:
print("")
print("Moeda estrangeira: {}".format(dolar_cot["code"]))
print("Moeda nacional: {}".format(dolar_cot["codein"]))
print("Moeda estrangeira: {}".format(dolar_cot["code"]))
print("Momento mais baixo: {}".format(dolar_cot["low"]))
print("Moeda mais alto: {}".format(dolar_cot["high"]))
print("Oferta: {}".format(dolar_cot["bid"]))
print("Pedido: {}".format(dolar_cot["ask"]))发布于 2020-09-06 10:56:20
这是您向API发送get请求时的响应
{"USD":{
"code":"USD",
"codein":"BRL","name":"Dólar Comercial",
"high":"5.327",
"low":"5.2477",
"varBid":"0.0104",
"pctChange":"0.2",
"bid":"5.3003",
"ask":"5.3033",
"timestamp":"1599253196",
"create_date":"2020-09-04 21:00:01"}
}如您所见,所有字段都嵌套在"USD"中。所以只需将dolar_cot = dolar.json()更改为dolar_cot = dolar.json()["USD"]
https://stackoverflow.com/questions/63760266
复制相似问题