Selenium WebDriver 测试中使用 Java 的 waitForVisible/waitForElementPresent 等价方法是什么?
Selenium webdriver 中有 waitForVisible/waitForElementPresent 的等效方法。它们是 Selenium 中同步概念的一部分。
隐式等待和显式等待是同步中的两种等待类型。
隐式等待是对 webdriver 应用的等待,用于所有元素的指定时间段。如果此时间过去后元素仍然不可用,则会抛出异常。
语法
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
示例
使用隐式等待的代码实现
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplctWait{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait of 5 secs
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.com/index.htm");
// identify element
WebElement m = driver.findElement(By.tagName("h4"));
System.out.println("Element text is: " + m.getText());
driver.quit();
}
}输出

显式等待是对 webdriver 应用的等待,用于元素满足预期条件的指定时间段。如果此时间过去后未满足预期条件,则会抛出异常。
waitForVisible 方法的等效方法可以在显式等待中使用 visibilityOfElementLocated 预期条件。同样,waitForElementPresent 方法的等效方法可以使用 presenceOfElementLocated 预期条件。
语法
WebDriverWait w= (new WebDriverWait(driver,5 ));
w.until(ExpectedConditions.presenceOfElementLocated(By.id("txt")));
w.until(ExpectedConditions.visibilityOfElementLocated (By.name("nam-txt")));示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExplicitWt{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//launch URL
driver.get("https://tutorialspoint.com/index.htm");
//explicit wait condition - presenceOfElementLocated
WebDriverWait w= (new WebDriverWait(driver, 7));
w.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[text()='Library']")));
WebElement m = driver.findElement(By.xpath("//*[text()='Library']"));
m.click();
//explicit wait condition - visibilityOfElementLocated
w.until(ExpectedConditions.visibilityOfElementLocated (By.linkText("Subscribe to Premium")));
WebElement n = driver.findElement(By.linkText("Subscribe to Premium"));
String s = n.getText();
System.out.println("Text is: " + s);
driver.quit();
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP