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

Selenium爬取仅获4个价格元素,如何获取全部71个?

解决Selenium爬取Urban Outfitters女装页面全部价格的方案

问题根源

该页面采用**懒加载(滚动加载)**机制,初始仅渲染可视区域内的商品,只有滚动页面触发加载后,才会显示更多商品及对应的价格元素,所以直接爬取只能拿到初始的4个结果。

具体实现方法

1. 循环滚动到底部加载全部内容

通过执行JavaScript代码滚动页面,配合判断页面高度变化来确认是否加载完成,示例代码:

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

driver = webdriver.Chrome()
driver.get("https://www.urbanoutfitters.com/womens-clothing")

last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # 滚动至当前页面底部
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # 等待页面加载新内容(可根据实际加载速度调整时长)
    time.sleep(3)
    # 获取新的页面高度
    new_height = driver.execute_script("return document.body.scrollHeight")
    # 高度不再变化则说明已加载全部
    if new_height == last_height:
        break
    last_height = new_height

# 提取所有价格元素文本
price_elements = driver.find_elements(By.XPATH, "//span[@class='c-price']")  # 替换为你实际使用的XPath
price_list = [elem.text.strip() for elem in price_elements if elem.text.strip()]
print(f"共获取{len(price_list)}个价格:")
print(price_list)

driver.quit()

2. 优化:用显式等待替代固定休眠

固定time.sleep()不够灵活,可通过等待新价格元素出现来优化,减少不必要的等待:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

# 初始化价格列表长度
prev_price_count = 0

while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    try:
        # 等待10秒,直到价格元素数量增加
        WebDriverWait(driver, 10).until(
            lambda d: len(d.find_elements(By.XPATH, "//span[@class='c-price']")) > prev_price_count
        )
        prev_price_count = len(driver.find_elements(By.XPATH, "//span[@class='c-price']"))
    except TimeoutException:
        # 超时无新元素加载,退出循环
        break

3. 精准滚动:滚动至最后一个价格元素

如果直接滚动到底部可能触发无效加载,可改为滚动到当前最后一个价格元素的位置,更精准:

price_elements = driver.find_elements(By.XPATH, "//span[@class='c-price']")
if price_elements:
    last_price = price_elements[-1]
    # 滚动到该元素可见位置
    driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'end'});", last_price)

注意事项

  • 控制滚动频率,避免因操作过快触发网站反爬机制
  • 确认价格元素的定位表达式(XPath/CSS选择器)正确,页面结构变化时需及时调整
  • 若网站有登录验证或Cookie限制,需提前处理相关逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:23:32