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

使用BeautifulSoup爬取DevCommunity时遇'NoneType'无text属性错误

解决BeautifulSoup爬取Dev.to时的'NoneType' object has no attribute 'text'错误

你遇到的问题根源是:部分被find_all抓取到的crayons-story元素里,并没有crayons-story__title这个子元素,导致x.find(class_="crayons-story__title")返回了None,后续直接调用title.text就触发了属性不存在的错误。

修复方案

给代码加上非空判断,确保只有在找到标题元素时才去获取文本:

from bs4 import BeautifulSoup
import requests

try:
    source = requests.get('https://www.dev.to')
    source.raise_for_status()
    
    soup = BeautifulSoup(source.text, 'html.parser')
    
    articles = soup.find_all(class_="crayons-story")
    for x in articles:
        title = x.find(class_="crayons-story__title")
        # 先判断标题元素是否存在,再提取文本
        if title:
            title_text = title.text.strip()
            print(title_text)
        # 可选:如果想给无标题的条目一个默认显示,也可以这么写
        # title_text = title.get_text(strip=True) if title else "无标题内容"
        # print(title_text)
except Exception as e:
    print(e)

关键修改点

  • 增加if title:的判断,过滤掉没有标题的条目,避免None类型调用属性的错误
  • 使用strip()方法去除文本前后的空白字符,让输出更整洁
  • 也可以用get_text()方法结合三元表达式,给无标题的情况设置默认值,进一步提升代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:22:39