调用commonteamroster接口获取NBA球队阵容仅返回2020赛季数据
问题原因与修复方案
你代码的问题出在循环拉取阵容的步骤遗漏了赛季参数:
- 仅首次调用
CommonTeamRoster获取球队ID时传入了season='2021-22'参数 - 后续
for循环遍历球队ID拉取阵容时,调用CommonTeamRoster没有传递season参数,接口会默认使用2020赛季返回数据,这就是你不管怎么改首次调用的赛季值,结果都只有2020赛季阵容的原因。
修复方法
将赛季定义为公共变量,循环调用时也传入该参数即可,修改后的核心代码如下:
import pandas as pd import requests import time headers = { 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'x-nba-stats-token': 'true', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36', 'x-nba-stats-origin': 'stats', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Referer': 'https://stats.nba.com/', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9', } from nba_api.stats.endpoints import commonteamroster # 定义公共赛季参数 TARGET_SEASON = '2021-22' # get teams from the reg season 2021-22 teamfinder = commonteamroster.CommonTeamRoster(season=TARGET_SEASON, team_id='1610612738', league_id_nullable='00') teams = teamfinder.get_data_frames()[0] team_ids = teams['TeamID'].unique().tolist() teams_roster=[] for team_id in team_ids: # 循环调用时传入赛季参数 player_stats_data = commonteamroster.CommonTeamRoster( season=TARGET_SEASON, team_id=team_id, headers=headers, timeout=100 ) time.sleep(.600) df = player_stats_data.common_team_roster.get_data_frame() df['TeamID'] = team_id print(team_id) teams_roster.append(df)
修改后再次运行就能拉取到对应赛季的球队阵容数据。
内容的提问来源于stack exchange,提问作者Bubbagaboosh
相关产品推荐
相关产品推荐

