调用LiveScore API触发JSONDecodeError问题求助
问题:Python脚本调用LiveScore API时触发JSONDecodeError
开发从LiveScore获取赛事信息的Python脚本时,遇到JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误。
报错堆栈信息
File "/home/sop/.local/lib/python3.8/site-packages/sopel/bot.py", line 763, in call_rule rule.execute(sopel, trigger) File "/home/sop/.local/lib/python3.8/site-packages/sopel/plugins/rules.py", line 1057, in execute exit_code = self._handler(bot, trigger) File "/home/sop/.local/lib/python3.8/site-packages/sopel/plugin.py", line 1071, in guarded return function(bot, trigger, *args, **kwargs) File "/home/sop/.sopel/plugins/livescores.py", line 310, in var data = get_match_info(id) File "/home/sop/.sopel/plugins/livescores.py", line 82, in get_match_info json = requests.get(url, headers=headers).json() File "/home/sop/.local/lib/python3.8/site-packages/requests/models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
相关代码片段
def get_match_info(id): data = {} url = f'https://prod-public-api.livescore.com/v1/api/app/match/soccer/{id}/0.0' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.5', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Cache-Control': 'max-age=0', 'TE': 'Trailers', } json = requests.get(url, headers=headers).json() kickoff = datetime.datetime.strptime(str(json['Esd']), '%Y%m%d%H%M%S') kickoff_utc = kickoff.replace(tzinfo=timezone('UTC')) kickoff_ro = kickoff_utc.astimezone(timezone('Europe/Bucharest')) data['country'] = json['Stg']['Cnm'] data['Esd'] = json['Esd'] data['league'] = json['Stg']['Snm'] if json['Eps'] == 'NS': data['time'] = ("Kick Off: " + str(kickoff_ro.time())[:-3]) else: data['time'] = json['Eps'] data['home_team'] = json['T1'][0]['Nm'] data['home_score'] = json['Tr1'] if "Tr1" in json else "0" data['away_team'] = json['T2'][0]['Nm'] data['away_score'] = json['Tr2'] if "Tr2" in json else "0" data['refs'] = json['Refs'][0]['Nm'] if "Refs" in json else 'VAR' return data
解决思路
这个错误说明requests.get()返回的内容不是有效JSON,大概率是请求失败、返回HTML错误页或空内容,按以下步骤排查修复:
先验证请求状态
在调用.json()前先检查响应状态码,触发HTTP错误提示:response = requests.get(url, headers=headers) response.raise_for_status() # 若返回403/404/503等会直接抛出异常如果是403拒绝访问,可能需要更新请求头(比如添加
Referer字段)、更换更贴近真实浏览器的UA,或者LiveScore API需要额外认证参数。查看真实响应内容
报错时打印返回内容,判断是错误页还是空值:response = requests.get(url, headers=headers) print(response.text) # 输出前200字符即可,快速定位问题如果返回Cloudflare验证页、登录提示或404页面,说明请求未通过服务端校验,需要调整请求逻辑。
增加异常捕获
避免脚本直接崩溃,同时记录错误信息:try: response = requests.get(url, headers=headers) response.raise_for_status() json_data = response.json() except requests.exceptions.HTTPError as e: print(f"HTTP请求失败: {e}") return None except json.JSONDecodeError: print(f"无效JSON响应: {response.text[:200]}") return None优化请求头
当前Accept字段偏向HTML请求,API接口通常需要JSON类型,修改为:'Accept': 'application/json, */*'同时移除
Upgrade-Insecure-Requests这类针对HTML页面的冗余头,让请求更贴合API调用场景。校验赛事ID有效性
确认传入的id参数是否正确,无效ID可能返回空内容或错误页,可手动在浏览器访问该URL验证是否返回正常JSON。
内容的提问来源于stack exchange,提问作者askingaquestion
相关产品推荐
相关产品推荐

