爬取Glomark商品信息报错求助:AttributeError问题排查
爬取Glomark商品数据时的AttributeError问题解决
问题描述
爬取https://glomark.lk/fresh/vegetable/low-country-vegetable/sc/799页面的商品名称、图片和价格时,运行代码触发如下错误:
AttributeError: 'NoneType' object has no attribute 'find'
错误指向代码第12行:product_name = product_name_element.find('span', class_='light-font').text.strip()
错误原因
product_name_element返回了None,说明部分div.item元素中找不到h3.product-title标签,或者找到的h3标签里不存在span.light-font子元素。直接对None调用find()方法就会触发AttributeError。
解决方法
通过增加空值判断,确保每个元素存在后再调用方法,同时补充价格爬取逻辑,修正后的代码如下:
from bs4 import BeautifulSoup as bs import requests link = "https://glomark.lk/fresh/vegetable/low-country-vegetable/sc/799" page = requests.get(link) soup = bs(page.content, 'html.parser') products = [] prices = [] images = [] for data in soup.findAll('div', class_='item'): # 处理商品名称 product_name_element = data.find('h3', class_='product-title') if product_name_element: product_name_span = product_name_element.find('span', class_='light-font') product_name = product_name_span.text.strip() if product_name_span else "商品名称未找到" else: product_name = "商品标题未找到" products.append(product_name) # 处理商品图片 image = data.find('img') image_src = image.get('src') if image and image.get('src') else "图片链接未找到" images.append(image_src) # 处理商品价格 price_element = data.find('span', class_='price') price = price_element.text.strip() if price_element else "价格未找到" prices.append(price) # 输出爬取结果 for idx, (name, price, img) in enumerate(zip(products, prices, images), 1): print(f"商品{idx}:") print(f" 名称: {name}") print(f" 价格: {price}") print(f" 图片: {img}\n")
关键改动说明
- 对每个HTML元素的查找结果都增加空值校验,避免
None调用方法报错 - 对无法获取的内容设置默认提示,保证程序能完整遍历所有商品
- 补充了原代码缺失的价格爬取逻辑,完成需求中的所有爬取目标
内容的提问来源于stack exchange,提问作者Milan_sir7
相关产品推荐
相关产品推荐

