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

调用Sofascore API时出现KeyError: normaltime问题求助

解决Sofascore足球API获取赛事数据时的KeyError问题

调用Sofascore足球赛事API获取2024-02-01的赛事数据时,访问分数数据中的normaltime、display和current字段会触发KeyError,原因是部分赛事的分数字段为空,导致代码运行中断。需求是获取这些字段的数值,若字段不存在则输出999。

修改后的代码

import requests 
import json
from datetime import datetime

url = "https://api.sofascore.com/api/v1/sport/football/scheduled-events/2024-02-01"

payload = ""
headers = {
    "authority": "api.sofascore.com",
    "accept": "*/*",
    "accept-language": "pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7",
    "cache-control": "max-age=0",
    "origin": "https://www.sofascore.com",
    "referer": "https://www.sofascore.com/",
    "sec-ch-ua-mobile": "?0",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 OPR/106.0.0.0"
}

response = requests.request("GET", url, data=payload, headers=headers)

jsondata = json.loads(response.text)

for game in jsondata['events']:
    league = game['tournament']['name']
    hometeam = game['homeTeam']['name']
    awayteam = game['awayTeam']['name']
    round = game['roundInfo']['round']
    # 使用get方法获取字段,不存在时返回999
    homescore = game['homeScore'].get('normaltime', 999)
    awayscore = game['awayScore'].get('normaltime', 999)
    homehalf = game['homeScore'].get('period1', 999)
    awayhalf = game['awayScore'].get('period1', 999)
    time = game['startTimestamp']

    print(league,"|", hometeam," - ",awayteam,"(",homehalf,"-",awayhalf,")",homescore,"-",awayscore,"|",datetime.fromtimestamp(time),"|",round)

关键修改说明

把原来直接通过字典['键']的字段访问方式,替换为字典.get('键', 默认值)方法。get()方法会在指定键不存在时返回预设的默认值(此处为999),不会抛出KeyError,确保代码能正常遍历所有赛事数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:37:34