如何在Selenium 4.0+Java 17环境中正确使用显式等待条件?
Selenium 4.0 显式等待正确配置方案
你当前代码用的是Selenium 3版本的显式等待API,Selenium 4对相关接口做了不兼容变更,按以下步骤修改即可:
1. 确认依赖引入
如果用Maven管理依赖,需要确保引入和你使用的Selenium核心版本一致的selenium-support包:
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-support</artifactId> <version>4.0.0</version> <!-- 和你项目中selenium-remote-driver的版本保持一致 --> </dependency>
2. 导入正确的依赖类
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration;
3. 修改显式等待相关代码
Selenium 4已经移除了直接传入整数秒数的WebDriverWait构造方法,必须传入Duration类型的超时参数,修正后的代码如下:
// 根据网页标题是否包含'BrowserStack'将测试状态设为'通过'或'失败' // 原错误写法:WebDriverWait wait = new WebDriverWait(driver, 5); // 修正写法,设置超时时间为5秒 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5)); try { // 取消注释即可正常调用显式等待 wait.until(ExpectedConditions.titleContains("BrowserStack")); jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Title matched!\"}}"); } catch(Exception e) { jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Title not matched\"}}"); }
可选优化
如果需要自定义轮询间隔、忽略指定异常,可以按如下方式配置:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5)) .pollingEvery(Duration.ofMillis(300)) // 每300ms轮询一次状态 .ignoring(NoSuchElementException.class); // 轮询过程中忽略找不到元素的异常
内容的提问来源于stack exchange,提问作者Asmoun
相关产品推荐
相关产品推荐

