显式等待会在 Web 网页中的某个特定元素上执行。
显式等待应用于 Web 网页中的某个特定元素。它将暂停执行,直至满足条件。显式等待也是动态的,因为如果等待时间为 15 秒,而条件(如等待元素可单击、可见或可选择等)在此指定时间之前得到满足,则控制权将转至下一步。
显式等待更具可定制性,因为我们可以根据条件进行设置。显式等待的一些预期条件如下 −
textToBePresentInElement()
语法
w.until(ExpectedConditions.textToBePresentInElement(By.id(“<<id expression>>“), “Tutorialspoint”));
textToBeClickable()
语法
w.until(ExpectedConditions.textToBeClickable(By.id(“<<id expression>>“)));
alertisPresent()
语法
w.until(ExpectedConditions.alertisPresent())= null);
frameToBeAvailableAndSwitchToIt()
语法
w.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id(“<<frame id >>“)));
在实现方面,显式等待很复杂,但它不会影响执行速度,并应用于页面上的特定元素。
在显式等待中,一旦超过最长时间,就会抛出 ElementNotVisibleException。
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Wait;
public class Explictwt {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://tutorialspoint.com/index.htm";
driver.get(url);
//implicit wait with time in seconds applied to each elements
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
//Clicking on Coding Ground link
driver.findElement(By.xpath("//span[text()=’Coding Ground’]")).click();
// explicit wait declaration
WebDriverWait w = new WebDriverWait(driver,10);
// condition to wait for with textToBePresentInElement method
w.until(ExpectedConditions.textToBePresentInElement(By.xpath("//img[@title=’Whiteboard’]"),” Whiteboard”));
driver.quit();
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP