显式等待原理
- 在代码中定义等待一定条件发生后再进一步执行代码
- 在最长等待时间内循环执行结束条件的函数
- WebDriverWait(driver 实例, 最长等待时间).until(结束条件函数)
显式等待-expected_conditions
public class WaitTest {
private static WebDriver driver;
private static WebDriverWait wait;
@BeforeAll
public static void setUpClas(){
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(1000));
}
@Test
void waitConditions(){
driver.get("https://vip.ceshiren.com/#/ui_study");
// 等待元素可被点击后,再点击按钮
wait.until(ExpectedConditions.elementToBeClickable(
By.cssSelector("#success_btn"))).click();
}
}
常见 expected_conditions
类型 |
示例方法 |
说明 |
element |
elementToBeClickable() |
|
visibilityOfElementLocated() |
针对于元素,比如判断元素是否可以点击,或者元素是否可见 |
|
url |
urlContains() |
针对于url |
title |
titleIs() |
针对于标题 |
frame |
frameToBeAvailableAndSwitchToIt() |
针对于frame |
alert |
alertIsPresent() |
针对于弹窗 |
显式等待-定制等待条件
- 官方的 ExpectedConditions 不可能覆盖所有场景
- 定制封装条件会更加灵活、可控
显式等待-定制等待条件
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class WaitTest {
private static WebDriver driver;
private static WebDriverWait wait;
@BeforeAll
public static void setUpClas() {
driver = new ChromeDriver();
wait = new WebDriverWait(driver, Duration.ofSeconds(1000));
}
@Test
void waitByLambda() {
driver.get("https://vip.ceshiren.com/#/ui_study");
wait.until((driver) -> {
driver.findElement(By.xpath("//*[text()='点击两次响应']")).click();
return driver.findElement(By.xpath("//*[text()='该弹框点击两次后才会弹出']"));
});
}
}
FluentWait等待
FluentWait简介
- 与显式等待近似
- 设定超时时间
- 设定轮询频率
- 忽略特定类型的异常
FluentWait使用场景
演示代码
public class WaitTest {
private static WebDriver driver;
// private static WebDriverWait wait;
@BeforeAll
public static void setUpClas() {
driver = new ChromeDriver();
// wait = new WebDriverWait(driver, Duration.ofSeconds(1000));
}
@Test
void fluentWait() {
driver.get("https://vip.ceshiren.com/#/ui_study");
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
//设置等待评估条件为真的时间 ---超时值
.withTimeout(Duration.ofSeconds(30))
//设置评估条件的频率 ---轮询频率
.pollingEvery(Duration.ofSeconds(5))
//忽略特定类型的异常
.ignoring(NoSuchElementException.class);
WebElement waring_ele = wait.until((driver)-> driver.findElement(By.id("warning_btn")));
waring_ele.click();
}
}