如何使用 Selenium 獲取 css 類名稱?


我們可以使用 Selenium webdriver 獲取某個元素的 css 類名稱。如需獲取 html 文件中某個元素的類名稱屬性,必須使用 getAttribute() 方法。然後將 class 值作為引數傳給方法。

讓我們考慮一下帶有類屬性的以下 html 程式碼。

類屬性的 value 值為 gsc-input。可以使用 getAttribute() 方法獲取該值。

示例

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 GetClssAttribute{
   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);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // get class attribute with getAttribute()
      String val = l.getAttribute("class");
      System.out.println("Class attribute value: " + val);
      driver.quit()
   }
}

輸出

更新於:2020 年 9 月 18 日

11K+ 檢視次數

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告