如何添加判断条件解决Python爬虫NoneType对象无text属性报错
问题修复方案
你遇到的报错原因是:当soup.find()找不到对应元素时会返回None,此时直接调用.text属性就会触发属性错误。你可以用异常捕获的方式直接跳过缺失字段的商品,修改后的可运行代码如下:
import requests import pandas as pd from bs4 import BeautifulSoup baseUrl = "https://www.sodimac.cl" # 修正headers格式,补全User-Agent键 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36' } productlinks =[] for x in range(1,7): r = requests.get(f"https://www.sodimac.cl/sodimac-cl/category/scat922339/Ceramicas?currentpage={x}", headers=headers) soup = BeautifulSoup(r.content, 'lxml') productlist = soup.find_all('div', class_='jsx-3663142191 search-results-products-container') for item in productlist: for link in item.find_all('a', id="title-pdp-link", href=True): productlinks.append(baseUrl + link['href']) Ceramicaslist = [] for link in productlinks: r = requests.get(link, headers=headers) soup = BeautifulSoup(r.content, 'lxml') try: # 把所有字段提取都放到try代码块里,任意一个字段缺失就直接跳过当前商品 name = soup.find('div', class_='jsx-4129468047 product-brand').text.strip() descripcion = soup.find('h1', class_='jsx-4129468047 product-title').text.strip() modelo = soup.find('div', class_='jsx-4129468047 product-model').text.strip() SKU = soup.find('div', class_='jsx-4129468047 product-cod').text.strip() precio = soup.find('span', class_='jsx-3655512908').text.strip() except AttributeError: # 捕获到缺失字段的异常,直接跳过当前循环,处理下一个商品链接 continue Ceramicas = { 'name': name, 'descripcion': descripcion, 'modelo': modelo, 'SKU': SKU, 'precio': precio } Ceramicaslist.append(Ceramicas) print('Saving: ', Ceramicas['name'], Ceramicas['descripcion'], Ceramicas['modelo'],Ceramicas['SKU'], Ceramicas['precio']) df = pd.DataFrame(Ceramicaslist) print(df) df.to_csv('CeramicasSodimac.csv', encoding='utf-8-sig')
核心修改点说明
- 补了缺失的
BeautifulSoup导入,修正了headers格式错误,请求时新增headers参数避免被网站拦截 - 在商品详情提取逻辑外层加了
try...except AttributeError捕获,任意一个字段提取失败(不存在text内容)就会触发continue跳过当前商品,不会打断整个爬取流程 - 修正了原代码里
Ceramicaslist.append的缩进错误,原代码缩进层级不对只会保存最后一个商品的信息 - 导出csv时新增
encoding='utf-8-sig'参数,避免打开时出现乱码问题
如果需要缺失字段时留空而不是跳过整个商品,可以单独给每个字段加判断,示例如下:
# 单个字段的判断写法,找不到就赋值为空字符串 name_tag = soup.find('div', class_='jsx-4129468047 product-brand') name = name_tag.text.strip() if name_tag else ''
内容的提问来源于stack exchange,提问作者Esteban García
相关产品推荐
相关产品推荐

