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

Python IF语句问题:NHL赛事数据爬取中缺失键的处理

解决NHL赛事数据爬取中提取非必填字段的IF判断问题

嘿,我来帮你搞定这个NHL数据爬取的小麻烦!你遇到的核心问题应该是直接访问不存在的字典键导致的KeyError,或者IF判断没兼顾到字段是否存在的情况——毕竟secondarytype只有射门(SHOT)类事件才会返回,其他事件里根本没有这个键。

先给你补全并修正后的完整脚本,咱们一步步说:

import csv
import requests
import os

# 请求赛事数据
req = requests.get('https://statsapi.web.nhl.com/api/v1/game/2017010001/feed/live')
data = req.json()
my_data = []
game_id = data['gameData']['game']['pk']

# 遍历所有赛事事件(NHL API里的事件都存在这个路径下)
for play in data['liveData']['plays']['allPlays']:
    play_result = play['result']
    event_type = play_result.get('eventTypeId')
    
    # 第一步:先判断当前事件是否是射门事件
    if event_type == 'SHOT':
        # 第二步:安全提取secondaryType——用字典的get方法,不存在则返回None
        shot_type = play_result.get('secondaryType')
        
        # 只有当射门类型存在时,才收集数据
        if shot_type is not None:
            # 组装你需要的数据字段
            collected_data = {
                'game_id': game_id,
                'event_id': play['about']['eventId'],
                'shot_type': shot_type
                # 可以添加其他你需要的字段,比如射门球员、时间等
            }
            my_data.append(collected_data)

# 将数据写入CSV文件
with open('nhl_shot_details.csv', 'w', newline='', encoding='utf-8') as csv_file:
    # 指定CSV表头
    field_names = ['game_id', 'event_id', 'shot_type']
    writer = csv.DictWriter(csv_file, fieldnames=field_names)
    writer.writeheader()
    writer.writerows(my_data)

关键修正点说明:

  • 用dict.get()替代直接键访问:play_result.get('secondaryType')会在键不存在时返回None,而不是抛出KeyError,这是处理非必填字典字段最安全的方式。
  • 分层判断逻辑:先判断事件类型是否为射门(event_type == 'SHOT'),再检查secondaryType是否存在且不为空,避免无效判断。

另外,如果你更习惯用“检查键是否存在”的方式,也可以把判断改成这样:

if event_type == 'SHOT' and 'secondaryType' in play_result:
    shot_type = play_result['secondaryType']
    # 后续处理...

这种方式和get()效果类似,都是避免访问不存在的键报错。

内容的提问来源于stack exchange,提问作者Michael T Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:17:13