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

出现AttributeError: 'NoneType'对象无'text'属性时如何爬取数据?

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

问题原因

你遇到的AttributeError是因为BeautifulSoup的find()方法在找不到目标元素时会返回None,此时直接调用.text属性就会触发错误。你的代码中没有处理元素找不到的情况,直接对find()结果调用.text,导致报错。

代码中的问题点

  • 变量名冲突:循环变量page被重新赋值为requests.get的响应对象,容易引发逻辑混乱
  • URL分页参数错误:原代码直接将页码拼在URL后,正确的分页参数应该是?page=页码
  • 未处理元素不存在的情况:所有find()调用后直接使用.text,一旦元素找不到就会报错
  • 空class匹配不可靠:item.find('h5', class_ ="")这种空class的匹配方式很难准确找到目标元素

修正后的代码

import pandas as pd
import requests
from bs4 import BeautifulSoup
from time import sleep
from random import randint

data = []
for page_num in range(1,5):
    print(page_num)
    # 修正分页参数格式
    response = requests.get(f"https://www.propertypro.ng/property-for-rent/commercial-property/office-space/in/abuja?page={page_num}")
    sleep(randint(2,10))

    soup = BeautifulSoup(response.content, 'html.parser')

    for item in soup.find_all('div', class_="single-room-sale listings-property"):
        # 逐个字段判断元素是否存在,避免None调用text
        price_elem = item.find('h3', class_="listings-price")
        price = price_elem.text.replace('/YEAR', '').strip() if price_elem else None

        title_elem = item.find('h4', class_="listings-property-title")
        title = title_elem.text.strip() if title_elem else None

        # 建议检查网页实际结构,替换成h5标签的真实class
        date_elem = item.find('h5', class_="")
        date_added = date_elem.text.strip() if date_elem else None

        contact_elem = item.find('div', class_="phone-icon text")
        contact = contact_elem.text.strip() if contact_elem else None

        data.append({
            'price': price,
            'title': title,
            'date_added': date_added,
            'contact': contact
        })

pd.set_option("display.max_rows", None)
df = pd.DataFrame(data)
print(df)

额外建议

  1. 打开目标网页的开发者工具,查看date_added对应的h5标签实际的class属性,替换代码中的空class,这样能更准确匹配元素
  2. 可以添加响应状态码检查,比如if response.status_code == 200:再继续解析,避免请求失败后处理无效内容
  3. 对于可能频繁变化的网页结构,建议定期检查元素选择器是否依然有效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:15:33