gpt4 book ai didi

python - 请求从列表中抓取多个元素

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:27 24 4
gpt4 key购买 nike

我在从此 liveData feed 中抓取所有 5 个 PlayerId 和持续时间时遇到问题。通过列出 [0] 元素,我可以获得 5 名玩家中的 1 名。我想在同一 header HomePlayerAwayPlayer 以及 HomeDurationAwayDuration 下同时获取所有 5 个。我尝试多次复制 HomePlayer 并将 [0] 更改为 [1] 但它只会刮掉它们,而不是同时刮掉两者,这是有道理的.

import requests
import csv

req = requests.get('https://statsapi.web.nhl.com/api/v1/game/2017020397/feed/live?site=en_nhl')
data = req.json()

my_data =[]

team_home, team_away = data['liveData']['boxscore']['teams']['home'], data['liveData']['boxscore']['teams']['away']

HomePlayer = team_home['onIcePlus'][0]['playerId']
AwayPlayer = team_away['onIcePlus'][0]['playerId']
HomeDuration = team_home['onIcePlus'][0]['shiftDuration']
AwayDuration = team_away['onIcePlus'][0]['shiftDuration']

my_data.append([HomePlayer, HomeDuration, AwayPlayer, AwayDuration])

headers = ["HomePlayer", "HomeDuration", "AwayPlayer", "AwayDuration"]

with open("NHL_2017020397_PbP_Shift.csv", "a", newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(my_data)
f.close()

最佳答案

您只能访问一名玩家的数据。所以它只是写入一位玩家的数据。

如果您确定将从 API 返回 5 条记录,请在 CSV block 内添加一个 for block ,以使用数组上的索引访问每个玩家的数据并一一写下来。

检查下面的代码。我将整个数据逻辑移至 CSV block 中,以循环播放玩家列表并将其写下来。

虽然这不是一种非常 Python 的方式,但您应该执行其余的查找操作以提高代码质量。

import requests
import csv

req = requests.get('https://statsapi.web.nhl.com/api/v1/game/2017020397/feed/live?site=en_nhl')
data = req.json()

team_home, team_away = data['liveData']['boxscore']['teams']['home'], data['liveData']['boxscore']['teams']['away']

headers = ["HomePlayer", "HomeDuration", "AwayPlayer", "AwayDuration"]

with open("/Users/kaybus/Desktop/NHL_2017020397_PbP_Shift.csv", "a", newline='') as f:
writer = csv.writer(f)
writer.writerow(headers)

for i in range(5):
HomePlayer = team_home['onIcePlus'][i]['playerId']
AwayPlayer = team_away['onIcePlus'][i]['playerId']
HomeDuration = team_home['onIcePlus'][i]['shiftDuration']
AwayDuration = team_away['onIcePlus'][i]['shiftDuration']
my_data =[]

my_data.append([HomePlayer, HomeDuration, AwayPlayer, AwayDuration])
writer.writerows(my_data)

关于python - 请求从列表中抓取多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614363/

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