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

英国Currys网站同URL分页切换失败技术求助

解决Currys网站无刷新分页切换问题

针对你爬取Currys网站独立式洗衣机页面时遇到的分页切换失败问题,以下是问题分析和可行解决方案:

原方法失败原因

  1. 选择器过于绝对:第一种方法的XPATH包含div[26]这类动态索引,页面元素数量变化后会直接失效;第二种方法的querySelector依赖多层级DOM结构,一旦页面布局微调就会找不到元素。
  2. 类名拼写错误:第二种方法中pagination-arrrow-next的arrrow应为arrow,拼写错误直接导致定位失败。
  3. 未处理元素可见性:分页按钮位于页面底部,未滚动到可见区域就直接点击,会导致操作无效。

可行解决方案

1. 使用稳定的元素定位方式

避免依赖动态索引或长层级结构,改用基于功能类名或文本的定位:

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 selenium.webdriver.common.action_chains import ActionChains
import time

driver = webdriver.Chrome()
driver.get("https://www.currys.co.uk/appliances/laundry/washing-machines/freestanding-washing-machines")

# 等待下一页按钮加载完成(用功能类名定位,避免拼写错误)
next_btn = WebDriverWait(driver, 15).until(
    EC.element_to_be_clickable((By.XPATH, "//li[contains(@class, 'pagination-arrow-next')]/a"))
)

# 滚动到按钮可见区域
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", next_btn)
time.sleep(1)  # 给页面滚动留缓冲时间

# 用ActionChains模拟人类点击(避免直接execute_script触发反爬)
ActionChains(driver).move_to_element(next_btn).click().perform()

# 等待页面更新(通过检测旧产品元素失效确认分页切换完成)
WebDriverWait(driver, 15).until(
    EC.staleness_of(driver.find_element(By.CSS_SELECTOR, ".product-list-item"))
)

# 后续爬取逻辑...
# driver.quit()

2. 处理反爬与页面加载

  • 若仍失败,可尝试使用undetected-chromedriver替代普通ChromeDriver,绕过网站的自动化检测。
  • 每次操作后添加随机等待(如time.sleep(random.uniform(1,3))),模拟人类浏览节奏。
  • 监控URL的hash变化(如#page=2),确认分页切换成功:
current_hash = driver.current_url.split("#")[-1]
WebDriverWait(driver, 15).until(
    lambda d: d.current_url.split("#")[-1] != current_hash
)

3. 备选方案:直接构造API请求

观察页面的XHR请求,Currys的产品数据通常通过API加载,可直接抓包获取分页API接口(如包含page参数的接口),无需模拟浏览器点击,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:03:20