如何从Riot Games API中提取数据?

问题描述 投票:0回答:1

我还是初学者,刚开始使用Python。我尝试通过JSON获得Riot Games(仅EUW)API的玩家等级和等级,但我得到一个例外:

print (responseJSON2[ID][0]['tier'])

TypeError: list indices must be integers or slices, not str

我不知道我要改变什么,也许有人可以帮助我:)代码:

import requests

def requestSummonerData(summonerName, APIKey):

    URL = "https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + summonerName + "?api_key=" + APIKey
    print (URL)
    response = requests.get(URL)
    return response.json()

def requestRankedData(ID, APIKey):
    URL= "https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/"+ID+"?api_key="+APIKey
    print (URL)
    response = requests.get(URL)
    return response.json()


def main():

    summonerName = (str)(input('Type your Summoner Name here: '))
    APIKey = (str)(input('Copy and paste your API Key here: '))
    responseJSON  = requestSummonerData(summonerName, APIKey)

    print(responseJSON)
    ID = responseJSON ['id']
    ID = str(ID)
    print (ID)
    responseJSON2 = requestRankedData(ID, APIKey)
    print (responseJSON2[ID][0]['tier'])
    print (responseJSON2[ID][0]['entries'][0]['rank'])
    print (responseJSON2[ID][0]['entries'][0]['leaguePoints'])


if __name__ == "__main__":
    main()
python json api python-requests
1个回答
0
投票

responseJSON2是一个list。列表包含索引(0,1,2,...)。

您需要为列表使用int:

ID = str(ID)

是错的,你需要有一个int!

尝试

ID = int(ID)

你可以转换回字符串:

def requestRankedData(ID, APIKey):
    URL= "https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/"+str(ID)+"?api_key="+APIKey
    print (URL)
    response = requests.get(URL)
    return response.json()

您需要在响应中找到与您的ID匹配的索引:

responseJSON2 = requestRankedData(ID, APIKey)
ID_idx = responseJSON2.index(str(ID))
print (responseJSON2[ID_idx][0]['tier'])
print (responseJSON2[ID_idx][0]['entries'][0]['rank'])
print (responseJSON2[ID_idx][0]['entries'][0]['leaguePoints'])
© www.soinside.com 2019 - 2024. All rights reserved.