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

求助:Python遍历Lazada单页商品循环失效(新手)

解决Lazada商品遍历失效问题

作为编程新手,在爬取Lazada商品时遇到遍历功能失效的问题:单个商品信息可以正常获取,但循环无法遍历所有商品,仅能拿到第一个商品的数据。

原代码

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup

url = 'https://www.lazada.com.ph/tag/tv/?q=tv&_keyori=ss&from=input&spm=a2o4l.home.search.go.7564ca18N2HNBJ&catalog_redirect_tag=true'

driver = webdriver.Chrome()
driver.get(url)

driver.implicitly_wait(3)


soup = BeautifulSoup(driver.page_source,"html.parser")
for item in soup.findAll('div',class_='Bm3ON'):
    title = soup.find('div',class_='RfADt').text
    price = soup.find('div',class_='aBrP0').text
    sold = soup.find('div',class_='_6uN7R').text
    
print(title,price,sold)
 
    
#for i in product:
    
driver.close()

问题分析

你的代码有两个核心问题导致遍历失效:

  • 循环内使用soup.find()而非item.find():soup.find()只会查找整个页面中第一个匹配的元素,所以每次循环都拿到同一个商品的信息。
  • print()语句在循环外部:即使循环逻辑正确,也只会打印最后一次循环的结果,无法输出所有商品数据。

修正后的代码

import time
from selenium import webdriver
from bs4 import BeautifulSoup

url = 'https://www.lazada.com.ph/tag/tv/?q=tv&_keyori=ss&from=input&spm=a2o4l.home.search.go.7564ca18N2HNBJ&catalog_redirect_tag=true'

driver = webdriver.Chrome()
driver.get(url)

driver.implicitly_wait(3)

soup = BeautifulSoup(driver.page_source,"html.parser")
# 遍历每个商品容器
for item in soup.findAll('div', class_='Bm3ON'):
    # 从当前商品容器内查找对应元素
    title = item.find('div', class_='RfADt').text.strip()
    price = item.find('div', class_='aBrP0').text.strip()
    # 处理可能不存在的销量字段,避免报错
    sold_elem = item.find('div', class_='_6uN7R')
    sold = sold_elem.text.strip() if sold_elem else '暂无销量'
    
    # 循环内部打印每个商品信息
    print(f"标题: {title}\n价格: {price}\n销量: {sold}\n---")
 
driver.close()

关键修改说明

  1. 替换查找对象:将soup.find()改为item.find(),确保从当前遍历的商品容器中提取信息,而非整个页面的第一个匹配项。
  2. 移动print位置:把print()放到循环内部,遍历到每个商品时立即打印其信息。
  3. 增加异常处理:对销量字段做判断,避免部分商品无销量时抛出AttributeError。

内容的提问来源于stack exchange,提问作者Franz Francisco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:15:22