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

Python变量设为None存入数据库Null时遇IndexError问题排查

问题分析与解决:列表索引越界错误

你的代码报错核心原因:re.split("- ", str(thesev))永远不会返回None,它始终返回一个列表——哪怕分割后的列表只有1个元素(当原字符串里没有- 分隔符时),甚至是空列表。所以你写的if thesevcat is None判断逻辑完全无效,当列表长度不足2时,访问thesevcat[1]就会触发IndexError。

修正方案

提供两种实用的修复写法:

写法一:检查列表长度

通过判断分割后列表的元素数量,确保索引访问安全:

thesev = cve.find("span", class_="label-warning").text
thesevcat = re.split("- ", str(thesev))

# 仅当列表元素数≥2时取索引1,否则设为None
if len(thesevcat) >= 2:
    thesevcat = thesevcat[1]
else:
    thesevcat = None

写法二:异常捕获

用try-except直接捕获索引越界异常,适合场景更复杂的情况:

thesev = cve.find("span", class_="label-warning").text
thesevcat = re.split("- ", str(thesev))

try:
    thesevcat = thesevcat[1]
except IndexError:
    thesevcat = None

额外优化(可选)

如果页面中可能存在找不到目标span标签的情况,建议提前处理find返回空的场景,避免触发AttributeError:

sev_elem = cve.find("span", class_="label-warning")
if sev_elem:
    thesev = sev_elem.text
    thesevcat = re.split("- ", str(thesev))
    try:
        thesevcat = thesevcat[1]
    except IndexError:
        thesevcat = None
else:
    thesevcat = None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:50:25