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

时间:2018-05-07 12:41:29

标签: python json api python-requests

我还是初学者,刚开始使用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()

2 个答案:

答案 0 :(得分:0)

responseJSON2list。列表包含索引(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'])

答案 1 :(得分:0)

这是我的代码:

from riotwatcher import LolWatcher()

region = str(input("Your region : ")) #If you only need EUW, just do region = "euw1"
summonerName = str(input("Your summonername : ")) #Asking for the user's summoner name
watcher = LolWatcher(api_key="your_api_key")
summonner = watcher.summoner.by_name(region=region, summoner_name=pseudo) #Getting account informations, you can print(summoner) to see what it gives
rank = watcher.league.by_summoner(region=region, encrypted_summoner_id=summonner["id"]) #User ranks using his id in summoner

tier = rank[0]["tier"]
ranklol = rank[0]["rank"]
lp = rank[0]["leaguePoints"]

print(f"{tier} {ranklol} {lp} LP")

应该没问题,我不知道你为什么要使用链接,使用 API 功能,这样更容易。希望能帮到你。