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

使用Beautiful Soup爬取商品价格返回空列表问题求助

解决爬取商品价格返回空列表的问题

问题根源

你的代码存在两个核心问题:

  • 元素层级定位错误:你用soup.find_all('div', class_="gallery-container shelf prateleira default n12colunas")获取的是整个商品列表的外层容器,而非单个商品的容器。在这个外层容器里直接查找price类的元素,自然无法定位到单个商品的价格。
  • 未等待页面完全加载:即便用了Selenium,页面可能还没加载完商品价格就获取了源码,导致价格元素未被解析到。

修正方案

  1. 定位单个商品容器:先找到页面中每个商品的独立容器(根据页面元素截图,单个商品的容器class为product-item),再在每个商品容器内提取价格。
  2. 添加显式等待:确保页面上的商品价格元素完全加载后再获取源码。
  3. 精准提取价格内容:价格元素内可能包含现价、原价等子元素,需定位到具体的价格文本节点。

修正后的代码

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup

url_pag='https://www.compracerta.com.br/celulares-e-smartphones?page=1'
executable_path = r'C:\Users\vinig\Downloads\chromedriver_win32\chromedriver.exe'
browser = webdriver.Chrome(executable_path=executable_path)
browser.get(url_pag)

# 显式等待,直到商品价格元素加载完成(等待最长10秒)
WebDriverWait(browser, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, "price"))
)

html = browser.page_source
soup = BeautifulSoup(html, 'lxml')

# 定位所有单个商品的容器
produtos = soup.find_all('div', class_="product-item")

for produto in produtos:
    # 提取商品品牌/名称(根据页面结构调整)
    marca = produto.find('a', class_="image")['title'] if produto.find('a', class_="image") else "无品牌信息"
    # 提取价格,优先取现价(current类),如果没有则取price容器内的文本
    preco_element = produto.find('div', class_="price")
    if preco_element:
        preco_atual = preco_element.find('span', class_="current")
        preco = preco_atual.get_text(strip=True) if preco_atual else preco_element.get_text(strip=True)
    else:
        preco = "无价格信息"
    print(f"商品:{marca},价格:{preco}")

browser.quit()

额外说明

  • 如果页面是滚动加载更多商品的动态页面,还需要添加滚动页面的逻辑,确保目标商品都被加载完成。
  • 注意网站的反爬机制,避免短时间内频繁请求导致IP被封禁。

内容的提问来源于stack exchange,提问作者Davi Riani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:17:22