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

如何用Python的Selenium点击分页页码?多种方法尝试均失败

解决Selenium点击分页页码无响应的问题

针对你遇到的Selenium无法触发分页页码点击的问题,结合提供的源码和代码,以下是几个可行的排查和修复方案:

1. 修正异常处理语法

你的代码中except NoSuchElementException or TimeoutException:存在语法错误,Python捕获多个异常需用括号包裹:

except (NoSuchElementException, TimeoutException):
    break

2. 使用更精准的显式等待

当前仅等待分页容器存在,未确保目标页码元素可交互。改为等待目标页码链接可点击,并增加滚动操作确保元素可见:

from selenium.webdriver.support import expected_conditions as EC

try:
    next_page_number = page_number + 1
    # 等待目标页码链接可点击
    next_page_link = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, f"page-link{next_page_number}"))
    )
    # 滚动到元素可见区域
    driver.execute_script("arguments[0].scrollIntoView(true);", next_page_link)
    next_page_link.click()
    # 等待页面切换完成(替换为等待当前活跃页码变化)
    WebDriverWait(driver, 10).until(
        EC.staleness_of(driver.find_element(By.CLASS_NAME, "active"))
    )
except (NoSuchElementException, TimeoutException):
    break

3. 更换定位方式(基于data属性)

避免依赖id,改用data-page-number属性定位li元素,再点击内部的a标签:

next_page_li = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, f"li.page-item[data-page-number='{next_page_number}']"))
)
driver.execute_script("arguments[0].scrollIntoView(true);", next_page_li)
next_page_li.find_element(By.TAG_NAME, "a").click()

4. 排查页面交互拦截

如果上述方法仍无效,可能是页面存在遮罩层或JS事件拦截:

  • 先关闭页面上的弹窗、Cookie提示等干扰元素
  • 尝试模拟真实用户的点击动作:
from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
actions.move_to_element(next_page_link).click().perform()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:47:24