gpt4 book ai didi

python - 分配简单变量命名后出现 KeyError

转载 作者:行者123 更新时间:2023-12-01 07:06:07 25 4
gpt4 key购买 nike

我已经很长时间没有使用 python 了,我正在尝试关注一个网站,从 ESPN 的 Fantasy Football 网站上抓取一些信息。我使用的网站是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()

我的预期结果是我每周调用的 5 列,通过 espn 网站填充 Score2。

回溯是:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com