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

时间:2017-12-03 01:20:42

标签: python python-requests

我遇到了从此liveData Feed中抓取所有5个PlayerId和持续时间的问题。通过列出[0]元素,我可以获得5个玩家中的1个。我想同时在同一标题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()

1 个答案:

答案 0 :(得分:1)

您只能访问一位玩家的数据。所以它只写了一个玩家的数据。

如果您确定将从API返回5条记录,则在for块内添加CSV块,以使用阵列上的索引访问每个播放器的数据并写入他们一个接一个地下来。

检查以下代码。我将整个数据逻辑移动到CSV块中,以循环播放列表并将其写下来。

虽然这不是一种非常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)