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

如何实现Selenium未找到元素时刷新页面循环重试点击功能

代码修改方案

首先需要导入Selenium对应的异常类与时间控制模块,通过while循环+异常捕获逻辑实现自动刷新重试,修改后的完整代码如下:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time

PATH = "C:\\Program Files (x86)\\chromedriver.exe" 
driver = webdriver.Chrome(PATH)

driver.get("URL")

# 无限循环重试,直到点击成功
while True:
    try:
        link = driver.find_element_by_link_text("Join")
        link.click()
        # 操作完成后退出循环
        break
    except NoSuchElementException:
        # 未找到元素时刷新页面
        driver.refresh()
        # 等待1秒后重试,可根据网络情况调整时长,避免触发反爬
        time.sleep(1)

可选优化:设置最大重试次数

如果不希望程序无限重试,可以添加最大重试次数限制,示例如下:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time

PATH = "C:\\Program Files (x86)\\chromedriver.exe" 
driver = webdriver.Chrome(PATH)

driver.get("URL")

max_retry = 100  # 自定义最大重试次数
retry_count = 0

while retry_count < max_retry:
    try:
        link = driver.find_element_by_link_text("Join")
        link.click()
        break
    except NoSuchElementException:
        driver.refresh()
        time.sleep(1)
        retry_count += 1
else:
    # 达到最大重试次数未成功时的处理逻辑
    print("已达到最大重试次数,未找到目标Join按钮")
    driver.quit()

注意事项

  • time.sleep()的时长可根据实际网络环境调整,网络较慢可以适当调大,避免页面还未加载完成就执行元素查找
  • 如果网站有反爬机制,可适当拉长等待间隔,避免请求过于频繁被限制访问

内容的提问来源于stack exchange,提问作者Johannes v.R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:54:03