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

如何使用Python+Selenium实现页面刷新直至alert弹窗不再显示

解决方案

问题根因

直接调用driver.switch_to.alert()会因为未做异常捕获和存在性判断,在页面未弹出alert时直接抛出NoAlertPresentException导致程序终止,同时也没有和页面刷新逻辑做联动,所以无法实现持续刷新直到alert消失的需求。

可运行实现代码

首先导入需要的依赖:

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

核心逻辑实现:

# 初始化Chrome驱动
driver = webdriver.Chrome()
driver.get("替换为你的目标页面URL")

# 可配置参数:最大重试次数、检测alert的超时时间
MAX_RETRY = 50
ALERT_WAIT_TIMEOUT = 3
retry_count = 0

while retry_count < MAX_RETRY:
    try:
        # 等待指定时长判断是否有alert弹出
        WebDriverWait(driver, ALERT_WAIT_TIMEOUT).until(EC.alert_is_present())
        # 存在alert,先关闭避免刷新时弹出二次确认框
        alert = driver.switch_to.alert
        print(f"检测到提示弹窗:{alert.text}")
        alert.accept()
        # 刷新页面
        driver.refresh()
        # 等待页面基础加载完成,可根据页面响应速度调整时长
        time.sleep(2)
        retry_count += 1
    except TimeoutException:
        # 等待超时说明无alert,跳出循环执行后续业务逻辑
        print("未检测到alert弹窗,继续执行后续代码")
        break
    except Exception as e:
        print(f"运行异常:{str(e)},重试中")
        driver.refresh()
        time.sleep(2)
        retry_count +=1

# 此处编写alert消失后的后续业务代码
# ...

# 全部逻辑执行完成后退出驱动
# driver.quit()

注意事项

  • 如果检测到的弹窗不是浏览器原生JS alert,而是前端用div模拟的自定义模态框,需要将alert检测逻辑替换为对应DOM元素的存在性判断,无需调用switch_to.alert相关方法
  • 可根据页面实际响应速度调整ALERT_WAIT_TIMEOUT和刷新后的等待时长,避免漏检alert
  • 若不需要限制重试次数,可以去掉MAX_RETRY相关判断,改为死循环直到alert消失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:51:03