顯式等待會在 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.tw/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(); } }
廣告