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

Python Selenium翻页点击失效问题求助

Selenium翻页点击失效问题排查与修复

问题点分析

  • 语法错误:点击方法未执行
    代码中next_page.find_element(By.XPATH("//a[@href='#']")).click只是引用了click方法,没有实际调用,必须改为.click()才能触发点击动作。

  • XPATH路径错误
    在子元素范围内查找时,使用//a[@href='#']会进行全局查找,应该改用相对路径.//a[@href='#'],限定在next_page元素的子节点中查找目标链接。

  • 等待方式不可靠
    硬编码的time.sleep()无法精准判断元素是否加载完成,建议用WebDriverWait显式等待元素可点击,提升稳定性。

修正后的完整代码

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 random
import time

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)

# 随机延迟范围
seconds = 1 + (random.random() * 2)

driver = webdriver.Chrome(options=chrome_options)
driver.implicitly_wait(30)

# 打开目标页面
driver.get("https://www.fda.gov/inspections-compliance-enforcement-and-criminal-investigations/compliance-actions-and-activities/warning-letters")
time.sleep(seconds)

# 显式等待"下一页"元素可点击,然后执行点击
wait = WebDriverWait(driver, 10)
next_page_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".next a")))
next_page_link.click()

# 解析当前页面(示例)
page_source = driver.page_source
soup = BeautifulSoup(page_source, "html.parser")
# 这里添加你的解析逻辑

# 后续翻页循环参考:
# while True:
#     try:
#         next_page_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".next a")))
#         next_page_link.click()
#         time.sleep(seconds)
#         # 解析新页面
#         page_source = driver.page_source
#         soup = BeautifulSoup(page_source, "html.parser")
#     except:
#         # 找不到下一页时退出循环
#         break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:45:34