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

BS4提取meta标签content属性报NoneType不可下标错误的解决方法

问题原因
  • 报错'NoneType' object is not subscriptable的核心原因是list_titles中存在None值,并非所有元素都是有效的BS4 Tag对象,直接用[]读取属性会触发异常。
  • 即使所有元素都是Tag对象,若部分Tag不存在content属性,也会触发类似报错。
正确写法

BS4提供get()方法用于安全读取标签属性,属性不存在/标签为None时会默认返回None,不会直接抛出异常。

基础遍历写法

content_list = []
for title in list_titles:
    # 先判断当前元素为有效Tag再取值
    if title:
        content = title.get('content')
        # 可选:过滤content为空的结果
        if content:
            content_list.append(content)

简化列表推导写法

content_list = [title.get('content') for title in list_titles if title and title.get('content')]
补充说明

你之前的tag['content']写法本身没有语法错误,只适用于完全确定所有Tag有效且一定存在content属性的场景,实际爬取场景下页面结构可能存在差异,更推荐用get()方法做容错处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:27:02