如何使用 Selenium 檢查元素是否包含特定的 class 屬性?
我們可以檢查一個元素是否包含特定的類屬性值。getAttribute() 方法用於獲取類屬性的值。我們需要將 class 作為引數傳遞給 getAttribute() 方法。
首先,我們需要使用任何定位符(如 id、class、name、xpath 或 css)來識別該元素。然後獲取該屬性的 class 值。最後,我們需要檢查該 class 屬性是否包含特定值。
我們以下面的 HTML 程式碼為示例,它包含 class 屬性。tp-logo 是 class 屬性的值。

示例
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 SpecificClassVal{
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/about/about_careers.htm");
// identify element
WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']"));
// get class attribute with getAttribute()
String clsVal = t.getAttribute("class");
//iterate through class value
for (String i : clsVal.split(" ")) {
//check the class for specific value
if (i.equals("tp-logo")) {
System.out.println("class attribute contains: " + clsVal);
} else {
System.out.println("class attribute does not contain: " + clsVal);}
}
driver.close();
}
}輸出

廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP