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.tw/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.tw/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