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

运行网络爬虫代码时出现NoneType对象无text属性错误

解决爬虫中的AttributeError: 'NoneType' object has no attribute 'text'

错误核心是job.find_next('span', class_='cm-post-date')未匹配到目标元素,返回了None,直接调用.text就会触发该异常。以下是几种实用的解决方式:

  • 前置存在性校验:在访问.text前先判断元素是否存在,避免空对象调用属性

    date_element = job.find_next('span', class_='cm-post-date')
    published_date = date_element.text.strip() if date_element else '未知发布日期'
    
  • 异常捕获处理:用try-except捕获AttributeError,针对性处理元素缺失的情况

    try:
        published_date = job.find_next('span', class_='cm-post-date').text.strip()
    except AttributeError:
        published_date = '未知发布日期'
    
  • 核对并调整选择器:检查目标网页的HTML结构,确认class名、标签是否正确,也可换用其他选择器语法

    # 示例:改用CSS选择器定位
    date_element = job.select_one('span.cm-post-date')
    published_date = date_element.text.strip() if date_element else '未知发布日期'
    

额外建议:爬取时加入简单日志,方便追踪缺失元素的页面,排查问题更高效

import logging
logging.basicConfig(level=logging.INFO)

date_element = job.find_next('span', class_='cm-post-date')
if not date_element:
    logging.info(f"页面未找到发布日期元素: {job}")
    published_date = '未知发布日期'
else:
    published_date = date_element.text.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:12:03