如何使用 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.com/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