You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python无法从ESPN API获取全部PGA球员数据问题排查

问题分析与解决

问题原因

代码的循环嵌套逻辑有误:遍历球员的循环结束后才执行字典创建和列表追加操作,此时playerName变量只会存储最后一位球员的名字,导致每个赛事仅生成一条包含最后一名球员的数据,而非所有参赛球员的记录。

解决思路

将创建单条记录字典和追加到列表的代码,移动到遍历球员的循环内部,确保每遍历到一名球员,就生成一条对应的赛事-球员记录并添加到列表中。

修正后的代码

import requests
import pandas as pd

# Define the API endpoint
api = 'https://site.web.api.espn.com/apis/site/v2/sports/golf/leaderboard?league=pga'

# Make a GET request and get the JSON response
response = requests.get(api)
data = response.json()

# Extract the events data, which contains the game details
events = data['events']

# Create an empty list to store the game data
games = []

# Loop through each event and get the relevant information
for event in events:
    # Get the game id, date, status, and competition
    game_id = event['id']
    date = event['date']
    name = event['name']
    for competition in event['competitions']:
        for competitor in competition['competitors']:
            athlete = competitor['athlete']
            playerName = athlete['displayName']
            # 将字典创建和追加操作移到球员循环内部
            game = {
                'game_id': game_id,
                'date': date,
                'name': name,
                'playerName': playerName
            }
            games.append(game)

# Convert the list of dictionaries into a pandas DataFrame
df = pd.DataFrame(games)

print(df)

内容的提问来源于stack exchange,提问作者Craig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:46:25