Selenium WebDriver 中等待變化的最佳實踐?


在 Selenium 中等待變化的最佳實踐是使用**同步**的概念。可以使用**隱式**和**顯式**等待來處理等待。隱式等待是應用於頁面上每個元素的全域性等待。

隱式等待的預設值為 0。它也是動態等待,這意味著如果隱式等待為 5 秒,而元素在第 3 秒可用,則立即執行下一步,無需等待完整的 5 秒。如果 5 秒後元素仍未找到,則會丟擲超時錯誤。

語法

driver.manage().timeouts().implicitlyWait();

示例

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 ImpctWt {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/index.htm");
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // findElement() will try to identify element till 5 secs
      WebElement n=driver.findElement(By.id("gsc−i−id1"));
      n.sendKeys("Java");
   }
}

顯式等待也用於頁面上的特定元素。它是一個與 Expected Condition 類一起工作的 WebDriverWait。它也是動態等待,這意味著如果顯式等待為 5 秒,而元素在第 3 秒可用,則立即執行下一步。如果 5 秒後元素仍未找到,則會丟擲超時錯誤。

顯式等待的一些預期條件如下:

  • titleContains(String s)

  • alertIsPresent()

  • invisibilityOfElementLocated(By locator)

  • invisibilityOfElementWithText(By locator, String s)

  • textToBePresentInElement(By locator, String t)

  • visibilityOfElementLocated(By locator)

  • presenceOfAllElementsLocatedBy(By locator)

  • visibilityOf(WebElement e)

  • presenceOfElementLocated(By locator)

  • elementToBeClickable(By locator)

  • stalenessOf(WebElement e)

示例

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 ExpltWt {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/index.htm");
      // identify element and click()
      driver.findElement(By.xpath("//*[text()='Library']")).click();
      // expected condition − invisibility condition
      WebDriverWait wt = new WebDriverWait(driver,5);
      // invisibilityOfElementLocated condition
      wt.until(ExpectedConditions.
      invisibilityOfElementLocated(By.xpath("//*[@class='mui−btn']")));
      driver.close();
   }
}

更新於:2020年11月28日

3K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告