【问题标题】:Python read data from API, typeError: list indices must be integers, not strPython 从 API 读取数据,typeError:列表索引必须是整数,而不是 str
【发布时间】:2019-04-05 22:14:18
【问题描述】:

我是 python 新手。我尝试从 api 读取一些数据,但在第二个 url 中有问题,我不知道当我有更多数据时如何解析 api。第一个 URL 只有一个“NAME”,第二个有多个 NAMES.... 我如何从第二个网址打印所有名称... 谢谢...

import os
from urllib import urlopen
import json

url = urlopen('https://www.coincalculators.io/api.aspx?name=ethereum&hashrate=420000000&power=0&poolfee=1&powercost=0&difficultytime=0').read()
data= json.loads(url)  
name = data["name"] # OK
print name
rewardsInMonth = data["rewardsInMonth"] # OK
print rewardsInMonth
#url with more names
url2 = urlopen('https://www.coincalculators.io/api/allcoins.aspx?hashrate=420000000&power=0&powercost=0&difficultytime=0&algorithm=Ethash').read()
data2= json.loads(url2)  
name2 = data2["name"] # OK
print name2

我看到第二个网址中有一个方括号,这对我来说是个问题。

【问题讨论】:

  • 你用的是什么版本的 Python?

标签: python api url


【解决方案1】:

此 API 的不同端点返回不同的数据结构。第一个调用只返回一个字典,第二个(到allcoins.aspx 端点)毫不奇怪的是一个字典列表。

非常礼貌地将您推向 Python 3 和 requests 模块的方向,第二个 URL 返回一个列表,因此您可以使用 for 循环遍历硬币:

import requests

coin = requests.get("https://www.coincalculators.io/api.aspx?name=ethereum&hashrate=420000000&power=0&poolfee=1&powercost=0&difficultytime=0").json()
print(coin["name"])

for coin in requests.get("https://www.coincalculators.io/api/allcoins.aspx?hashrate=420000000&power=0&powercost=0&difficultytime=0&algorithm=Ethash").json():
    print(coin["name"])

【讨论】:

  • 谢谢!现在工作-我看到打印所有“名称”。现在我有第二个问题。所有“名称”(硬币)都有自己的“profitInDayUSD”。而且我必须将硬币的所有利润转换为浮动......“名称”=浮动“利润InDayUSD”......然后我必须插入IF函数(如果一些硬币有更大的“利润InDayUSD”然后是“2美元”,设置输出打开(Rassberry Pi),将继电器切换到打开,PC 开始挖矿 :) 我有很多工作.... :)
  • if float(coin["profitInDayUSD"]) > 2.0: start_mining(coin["name"]) :-)
猜你喜欢
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 2014-09-02
相关资源
最近更新 更多