如何使用 WebDriver 檢查元素是否可見?


我們可以使用 Selenium webdriver 檢查元素是否存在。有多種方法可以檢查它。我們將使用同步中的顯式等待概念來驗證元素的可見性。

讓我們考慮以下網頁元素並檢查它是否在頁面上可見。有一個名為 visibilityOfElementLocated 的條件,我們將使用它來檢查元素的可見性。它將在指定的時間內等待元素,之後它將丟擲異常。

我們需要 **import org.openqa.selenium.support.ui.ExpectedConditions** 和 **import org.openqa.selenium.support.ui.WebDriverWait** 來整合預期條件和 WebDriverWait 類。我們將引入一個 try/catch 塊。在 catch 塊中,如果元素在頁面上不可見,我們將丟擲 **NoSuchElementException**。

我們還可以藉助 isDisplayed() 方法確認元素是否可見。此方法返回 true 或 false 值。如果元素不可見,則該方法返回 false 值。

讓我們檢查以下元素是否可見 -

示例

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;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.NoSuchElementException;

public class CheckVisibile{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      driver.get("https://tutorialspoint.tw/index.htm");
      try {
         // identify element
         WebElement t = driver.findElement(By.cssSelector("h4"));
         // Explicit wait condition for visibility of element
         WebDriverWait w = new WebDriverWait(driver, 5);
         w.until(ExpectedConditions .visibilityOfElementLocated(By.cssSelector("h4")));
         System.out.println("Element is visible");
      }
      catch(NoSuchElementException n) {
         System.out.println("Element is invisible");
      }
      driver.close();
   }
}

示例

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 CheckIsDisplayed{
   public static void main(String[] args) {
         System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
         WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
         driver.get("https://tutorialspoint.tw/index.htm");
         // identify element
         try {
            WebElement t = driver.findElement(By.cssSelector("h4"));
            // check visibility with isDisplayed()
            if (t.isDisplayed()){
               System.out.println("Element is visible");
         }
         catch(Exception n)   {
            System.out.println("Element is invisible");
         }
      driver.close();
   }
}

輸出

更新於: 2020年9月18日

7K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告