更新时间:2023-11-25 23:35:52
鉴于您已找到您的元素,并且您想检查class-attribute中的某个类:
Given you already found your element AND you want to check for a certain class inside the class-attribute:
public boolean hasClass(WebElement element) {
String classes = element.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals(theClassYouAreSearching)) {
return true;
}
}
return false;
}
正如@aurelius正确指出的那样,有一种更简单的方法(效果不佳):
As @aurelius rightly pointed out, there is an even simpler way (that doesn't work very well):
public boolean elementHasClass(WebElement element, String active) {
return element.getAttribute("class").contains(active);
}
这种方法看起来更简单,但有一个很大的警告:
This approach looks simpler but has one big caveat:
正如@JuanMendes所指出的,如果您要搜索的类名是其他类名的子字符串,则会遇到问题:
As pointed out by @JuanMendes you will run into problems if the class-name you're searching for is a substring of other class-names:
例如class =test-a test-b,搜索class.contains(test)将返回true但它应该为false
for example class="test-a test-b", searching for class.contains("test") will return true but it should be false