如何驗證一個元素是否在 Selenium 中顯示在螢幕上?


我們可以藉助以下列出的方法幫助驗證 Web 元素(如編輯框、複選框和單選按鈕等)是否可見 −

  • isDisplayed()

    此方法檢查 Web 元素是否顯示在螢幕上。

    語法 −

    Boolean result = driver.findElement(By.xpath("//span[text()=’Coding Ground’]")).isDispayed();
  • isSelected()

    此方法檢查靜態下拉選單中單選按鈕、複選框和選項的狀態。

    語法 −

    Boolean btnresult = driver.findElement(By.xpath("//xpath[contains(@class,’gsc-search-button’)]")).isSelected();
  • isEnabled()

    語法 −

    Boolean btnresult = driver.findElement(By.xpath("//xpath[contains(@class,’gsc-search-button’)]")).isEnabled();

此方法檢查一個元素是否已啟用。

示例

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 ElementStatus{
   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/tutor_connect/index.php";
      // to verify if a static dropdown is selected with option isSelected()
      boolean drpdwnStatus = driver.findElement(By.xpath("//select[@name=’selType’]"))
      .isSelected();
      // to verify if an element is present on page with isDisplayed()
      boolean editStatus = driver.findElement(By.xpath("//input[@id=’txtSearchText’]"))
      .isDisplayed();
      // to verify if a button is enabled with isEnabled()
      boolean butnStatus = driver.findElement(By.xpath("//input[@id=’searchSubmit’]"))
      .isEnabled();
      System.out.println("The button status is " + butnStatus);
      System.out.println
      ("The dropdown selected status is" + drpdwnStatus);
      System.out.println("The edit box display status is " + editStatus);
      driver.close();
   }
}

更新時間: 2020 年 6 月 11 日

已檢視 9K+ 次

開始您的事業

透過完成課程獲得認證

開始
廣告