如何使用 Selenium 获取 CSS 类名?

seleniumautomation testingtesting tools更新于 2026/2/11 16:07:17

我们可以使用 Selenium WebDriver 获取元素的 CSS 类名。要获取 HTML 文档中元素的类名属性,我们必须使用 getAttribute() 方法。然后将 class 值作为参数传递给该方法。

让我们考虑以下带有 class 属性的 HTML 代码。

class 属性的值为 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://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // 识别元素
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // 使用 getAttribute() 获取类属性
      String val = l.getAttribute("class");
      System.out.println("Class attribute value: " + val);
      driver.quit()
   }
}

输出


相关文章