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

Selenium中切换到弹出含Alert的新窗口时获取窗口句柄超时的问题求助

Selenium中切换到弹出含Alert的新窗口时获取窗口句柄超时的问题求助

我现在在做一个Selenium自动化场景:点击某个操作后会触发弹出新窗口,但这个新窗口因为直接抛出了浏览器Alert(这是预期的正常情况),所以根本没加载任何内容。我需要验证这个Alert确实出现了,于是写了这段代码:

WebDriver driver = SeleniumSession.get().getWrappedDriver();
List<String> handles = new ArrayList<String>(driver.getWindowHandles());

int i = 0;
for (String handle : handles) {
    if (i == 1) {
        driver.switchTo().window(handle);
        Alert alert = driver.switchTo().alert();
        alert.accept();
    }
    i++;
}

但我遇到了棘手的问题:List<String> handles = new ArrayList<String>(driver.getWindowHandles());这行代码直接抛出了TimeoutException,异常信息是:
org.openqa.selenium.TimeoutException: java.util.concurrent.TimeoutException

我之前在一个讨论串里看到过一模一样的问题,但那个帖子最后没找到解决方案,而且我因为账号权限不够没法在下面评论提问。

我自己试了好几种办法都没能解决:

  • 在获取窗口句柄前加了隐式等待,想着等内容加载完成再获取
  • 给getWindowHandles()加了try-catch块,打算在捕获到异常时重试获取操作
  • 尝试不切换到新窗口,直接获取Alert

但不管试哪种方案,都会触发这个TimeoutException。

备注:内容来源于stack exchange,提问作者Tisaja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 20:12:58