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

BeautifulSoup使用item.find时报NoneType无text属性如何解决

解决BeautifulSoup取text时报NoneType属性错误的方案

完全可以在不改动原有company对象结构的前提下实现空值校验,避免报错,以下是两种常用的低改造成本方案:

方案1:用getattr快速校验(无额外函数定义,改动最小)

利用Python内置的getattr方法,仅执行一次查找操作,找不到对应元素时自动返回默认空值,修改后代码如下:

trucking_companies = soup.find_all('div',{'class' : 'well well-sm' })
for item in trucking_companies:
   company = {
   'name': getattr(item.find('span', { 'itemprop': 'name'}), 'text', ''),
   'street address': getattr(item.find('span', {'itemprop': 'streetAddress'}), 'text', ''),
   'city': getattr(item.find('span', {'itemprop': 'addressLocality'}), 'text', ''),
   'state': getattr(item.find('span', {'itemprop': 'addressRegion'}), 'text', ''),
   'zip' : getattr(item.find('span', {'itemprop': 'postalCode'}), 'text', ''),
   'phone': getattr(item.find('b', {'itemprop': 'telephone'}), 'text', ''),
   'fax' : getattr(item.find('b', {'itemprop': 'faxNumber'}), 'text', ''),
   }
   print(company)

说明:末尾的空字符串''是默认占位值,你也可以根据需求替换为None、'无'等其他值。

方案2:封装通用取值函数(适合字段多的场景,减少重复代码)

如果后续还要新增更多提取字段,可以提前封装一个通用的取值工具函数,逻辑更清晰:

# 提前定义通用取值函数
def get_text(item, tag, attrs):
    element = item.find(tag, attrs)
    return element.text if element else ''

trucking_companies = soup.find_all('div',{'class' : 'well well-sm' })
for item in trucking_companies:
   company = {
   'name': get_text(item, 'span', { 'itemprop': 'name'}),
   'street address': get_text(item, 'span', {'itemprop': 'streetAddress'}),
   'city': get_text(item, 'span', {'itemprop': 'addressLocality'}),
   'state': get_text(item, 'span', {'itemprop': 'addressRegion'}),
   'zip' : get_text(item, 'span', {'itemprop': 'postalCode'}),
   'phone': get_text(item, 'b', {'itemprop': 'telephone'}),
   'fax' : get_text(item, 'b', {'itemprop': 'faxNumber'}),
   }
   print(company)

两种方案都完全保留了原有company字典的键结构,不会影响后续的逻辑处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:18:02