首页 > 解决方案 > 我正在尝试制作一个程序来显示美元价值,但我无法让它向我打印我想要的信息

问题描述

所以,这是脚本。我正在使用我在互联网上找到的这个 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"]))

标签: pythonpython-requests

解决方案


这是您向 API 发送获取请求时的响应

{"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"]


推荐阅读