我已经很长时间没有使用python了,我正试图跟随一个网站从ESPN的梦幻足球网站上抓取一些信息。我正在使用的wesbite是https://stmorse.github.io/journal/espn-fantasy-v3.html。当我尝试下面列出的代码时,出现KeyError:“ schedule”。
我尝试完全按照网站上的代码进行操作,但给出了相同的错误。我在https://fantasy.espn.com/apis/v3/games/ffl/seasons/2019/segments/0/leagues/14380834?view=mMatchup上打开了api,并看到有安排的地方,所以不确定我还需要做什么。
league_id = 14380834
year = 2019
url = "https://fantasy.espn.com/apis/v3/games/ffl/seasons/2019/segments/0/leagues/14380834/"
r = requests.get(url)
d = r.json()
r = requests.get(url, params={"view": "mMatchup"})
df = [[
game['matchupPeriodId'],
game['home']['teamId'], game['home']['totalPoints'],
game['away']['teamId'], game['away']['totalPoints']
] for game in d['schedule']]
df = pd.DataFrame(df, columns=['Week', 'Team1', 'Score1', 'Team2', 'Score2'])
df['Type'] = ['Regular' if w<=14 else 'Playoff' for w in df['Week']]
df.head()
我的预期结果将是我本周要求通过espn网站填充得分2的5列。
追溯为:
File "C:/Users/jacob/PycharmProjects/FF_stuff/app.py", line 15, in <module>
] for game in d['schedule']]
KeyError: 'schedule'
Process finished with exit code 1
最佳答案
您需要从包含参数而不是第一个请求的请求中获取json d
。
这有效
r = requests.get(url, params={"view": "mMatchup"})
d = r.json()
df = [[
game['matchupPeriodId'],
game['home']['teamId'], game['home']['totalPoints'],
game['away']['teamId'], game['away']['totalPoints']
] for game in d['schedule']]
df = pd.DataFrame(df, columns=['Week', 'Team1', 'Score1', 'Team2', 'Score2'])
df['Type'] = ['Regular' if w<=14 else 'Playoff' for w in df['Week']]
df.head()
KeyError
即将到来,因为没有参数的请求中没有'schedule'
信息。您可以执行d.keys()
来查看dict
具有哪些键关于python - 分配简单变量命名后的KeyError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58438633/