Selenium使用FluentWait仍抛出NoSuchElementException问题咨询
问题
使用FluentWait等待DOM元素加载时,已设置忽略NoSuchElementException和ElementNotInteractableException,但控制台仍输出NoSuchElementException报错信息,不过最终测试能定位到元素并通过,疑惑为何明确忽略仍会输出错误。
代码片段:
Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(15)) .pollingEvery(Duration.ofMillis(500)) .ignoring(ElementNotInteractableException.class, NoSuchElementException.class);
报错栈:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[class="fsrAbandonButton"]"} (Session info: headless chrome=118.0.5993.88)
解决分析
- 忽略异常的作用边界:FluentWait的
ignoring()方法仅控制等待逻辑不会因指定异常终止,不会阻止Selenium底层将异常信息打印到控制台。轮询查找元素时,每次找不到元素仍会抛出异常,但FluentWait会捕获这些异常并继续等待,直到超时前找到元素或到达等待上限。 - 日志输出的本质:你看到的报错是Selenium的日志打印,并非测试代码抛出的未捕获异常。测试最终通过,说明FluentWait的忽略逻辑生效了,之前的异常都被正确处理,未影响等待流程。
- 屏蔽这类日志的方法:若不想看到此类日志,可调整Selenium的日志级别。以ChromeDriver为例,通过
ChromeOptions设置日志级别为SEVERE,仅输出严重错误:
ChromeOptions options = new ChromeOptions(); options.setLogLevel(Level.SEVERE); WebDriver driver = new ChromeDriver(options);
也可通过系统属性配置:
System.setProperty("webdriver.chrome.logLevel", "SEVERE");
内容的提问来源于stack exchange,提问作者Kyle
相关产品推荐
相关产品推荐

