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

使用Selenium与Python无法提取Nike网站价格数据的技术问询

Nike英国官网运动鞋价格爬取问题解决方案

问题根源分析

原代码失败主要有几个核心问题:

  • 依赖绝对XPath定位元素,Nike官网的DOM结构随时可能调整,绝对路径极易失效;
  • 未处理页面加载时的Cookie同意弹窗,弹窗会遮挡或干扰元素定位;
  • 使用presence_of_element_located仅确认元素存在,但元素可能还未渲染出文本内容;
  • df.append方法已被Pandas弃用,可能导致数据写入异常;
  • 裸except捕获所有异常,无法定位具体失败原因。

修复后的完整代码

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
import pandas as pd

# 初始化浏览器
browser = webdriver.Chrome()
# 用列表收集数据,比append更高效稳定
data_list = []

# 目标商品页面
websites = [
    'https://www.nike.com/gb/t/dunk-low-retro-shoe-Kd1wZr/DD1391-103',
    'https://www.nike.com/gb/t/dunk-low-retro-shoe-QgD9Gv/DD1391-100',
    'https://www.nike.com/gb/t/dunk-low-retro-shoes-p6gmkm/DV0833-400'
]

for website in websites:
    browser.get(website)
    try:
        # 处理Cookie同意弹窗(优先点击拒绝,避免不必要的加载)
        try:
            cookie_btn = WebDriverWait(browser, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//button[text()="Reject All"]'))
            )
            cookie_btn.click()
        except:
            # 若弹窗未出现,跳过
            pass
        
        # 用稳定的属性选择器定位价格(优先用data-testid,比class更可靠)
        price_element = WebDriverWait(browser, 20).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, 'span[data-testid="current-price"]'))
        )
        price_text = price_element.text.strip()
        
        # 收集商品名称(从页面标题提取,比URL更友好)
        product_name = browser.title.split("|")[0].strip()
        
        # 添加到数据列表
        data_list.append({"Product": product_name, "Price": price_text})
        print(f"成功获取 {product_name} 的价格:{price_text}")
    
    except Exception as e:
        # 打印具体异常信息,方便调试
        print(f"获取 {website} 价格失败:{str(e)}")

# 关闭浏览器
browser.quit()

# 转换为DataFrame并保存CSV
df = pd.DataFrame(data_list)
df.to_csv('PriceList.csv', index=False, encoding='utf-8-sig')
print("数据已成功保存到PriceList.csv")

关键修改说明

  • 替换绝对XPath为CSS属性选择器:使用span[data-testid="current-price"]定位价格,这是Nike官方用于测试的标识,比DOM路径稳定得多;
  • 处理Cookie弹窗:强制等待并点击拒绝按钮,避免弹窗干扰后续元素定位;
  • 改用visibility_of_element_located:确保元素不仅存在,而且可见且文本已渲染完成;
  • 用列表收集数据:替代已弃用的df.append,提升性能和稳定性;
  • 捕获具体异常:打印错误详情,便于排查定位失败的具体原因;
  • 提取页面标题作为商品名称:比直接用URL更直观友好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:02:53