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

网页爬取返回空DataFrame求助:如何获取指定商品数据?

解决爬取Ceneo.pl笔记本数据得到空DataFrame的问题

问题原因

  • 页面元素的CSS类名可能已更新,原选择器无法匹配到目标元素
  • Selenium直接获取页面源码时,页面可能尚未完全渲染完成
  • 部分商品无评分,直接调用.text会引发异常导致程序中断

修正后的代码

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

# 初始化浏览器
driver = webdriver.Chrome()
driver.get("https://www.ceneo.pl/Laptopy;0020-30-0-0-1.htm")

# 等待页面核心商品元素加载完成(最多等待10秒)
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "cat-prod-row"))
    )
except Exception as e:
    print("页面加载超时:", e)
    driver.quit()
    exit()

# 获取完全渲染后的页面源码
content = driver.page_source
soup = BeautifulSoup(content, features="lxml")

names = []
prices = []
ratings = []

# 遍历每个商品条目(匹配当前页面的商品容器)
for product in soup.find_all('article', class_='cat-prod-row js_cat-prod-row'):
    # 提取商品名称,处理无名称的情况
    name_elem = product.find('a', class_='cat-prod-row__name go-to-product js_conv js_clickHash js_seoUrl')
    names.append(name_elem.text.strip() if name_elem else "无名称")
    
    # 提取商品价格,处理无价格的情况
    price_elem = product.find('span', class_='price-value')
    prices.append(price_elem.text.strip() if price_elem else "无价格")
    
    # 提取商品评分,处理无评分的情况
    rating_elem = product.find('span', class_='product-score')
    ratings.append(rating_elem.text.strip() if rating_elem else "无评分")

# 生成DataFrame并输出
df = pd.DataFrame({
    "商品名称": names,
    "价格": prices,
    "评分": ratings
})

print(df)

# 关闭浏览器
driver.quit()

关键调整说明

  • 添加页面等待:用WebDriverWait确保商品元素加载完成后再抓取源码,避免动态渲染导致的元素缺失
  • 更新选择器:根据当前Ceneo.pl页面的实际元素类名调整定位规则,确保能匹配到目标数据
  • 空值处理:对可能不存在的元素(如无评分商品)做判空处理,避免程序因报错中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:01:20