WebDriver_Selenium 元素等待
WebDriver元素等待有四种方式:
- 强制等待
- 隐式等待
- 显式等待
- 流利等待
一、强制等待
try {
//强制等待5s
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
强制等待不足之处:
- 不灵活
- 如果等待时间不足,程序会报错
- 如果等待时间过长,自动化测试的效率会非常低
二、隐式等待
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
三、显式等待
By location = By.xpath("")
1. 显式等待
WebElement foo = new WebDriverWait(driver, Duration.ofSeconds(3))
.until(driver -> driver.findElement(location));
2. 判断某个元素中是否可见并且是enable的,这样的话才叫clickable;
WebElement foo = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(location));
3. 判断元素是否出现,只要有一个元素出现,就通过。(代表在不代表可见)
WebElement foo = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.presenceOfElementLocated(location));
4. 判断元素是否出现。
List<WebElement> eleList = new WebDriverWait(driver, timeOutInSeconds)
.until(ExpectedConditions.presenceOfAllElementsLocatedBy(location));
5. 判断某个元素是否可见. 可见代表元素非隐藏,并且元素宽和高都不等于 0
WebElement foo = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.visibilityOfElementLocated(location));
四、流利等待
// 等待30秒,等待元素出现在页面上,检查每5秒出现一次。
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(location);
}
});