Python中如何处理'NoneType' object is not subscriptable报错
报错规避处理方案
可能触发报错的场景
代码运行时会从以下几个环节抛出异常:
- 遍历得到的
t子元素数量不足10,访问t[4]/t[7]/t[8]/t[9]时触发索引越界 t[4].find("a")/t[7].find("a")未匹配到a标签,返回None后访问href属性报错- 匹配到的a标签没有href属性,直接用
["href"]取值抛出KeyError - href字符串按
/分割后的列表长度不足5,访问索引[4]时触发索引越界
方案1:保留异常条目,缺省字段填充默认值
先封装通用的ID提取工具函数,对每一步可能出错的环节做判断,取不到值时返回默认占位符(可自定义为None、空串或其他业务需要的占位值):
def get_team_id(td_ele, default=""): # 先判断td元素是否存在 if not td_ele: return default # 查找a标签,未找到返回默认值 a_tag = td_ele.find("a") if not a_tag: return default # 用get方法取href属性,不存在则返回None href = a_tag.get("href") if not href: return default # 分割后判断长度是否满足取索引4的要求 href_parts = href.split("/") return href_parts[4] if len(href_parts) >=5 else default
修改原有extend逻辑:
PlayersTransferhistoryResult.extend([ { "pId": pid[4], "Season": t[0].text.strip(), "Date": t[1].text.strip(), "Left": t[4].text.strip(), "LeftId": get_team_id(t[4]), "Joined": t[7].text.strip(), "JoinedId": get_team_id(t[7]), "MV": t[8].text.strip(), "Fee": t[9].text.strip(), } for t in (t.find_all(recursive=False) for t in tr) # 过滤长度不足10的t,避免访问高索引时越界 if len(t) >= 10 ])
方案2:直接过滤无效条目
如果不符合取值要求的条目不需要保留,可以在列表推导式的过滤条件中加上合法性校验,直接跳过异常条目:
def is_valid_item(t): if len(t) < 10: return False # 校验LeftId取值合法性 left_a = t[4].find("a") if not left_a or not left_a.get("href") or len(left_a.get("href").split("/")) <5: return False # 校验JoinedId取值合法性 joined_a = t[7].find("a") if not joined_a or not joined_a.get("href") or len(joined_a.get("href").split("/")) <5: return False return True PlayersTransferhistoryResult.extend([ { "pId": pid[4], "Season": t[0].text.strip(), "Date": t[1].text.strip(), "Left": t[4].text.strip(), "LeftId": t[4].find("a")["href"].split('/')[4], "Joined": t[7].text.strip(), "JoinedId": t[7].find("a")["href"].split('/')[4], "MV": t[8].text.strip(), "Fee": t[9].text.strip(), } for t in (t.find_all(recursive=False) for t in tr) if is_valid_item(t) ])
内容的提问来源于stack exchange,提问作者Mehdi Arfaei
相关产品推荐
相关产品推荐

