如何检查元素是否包含特定的类属性 [英] How to check if element contains specific class attribute
问题描述
如何检查selenium web元素是否包含特定的css类。
How can I check if a selenium web element contains a specific css class.
我有这个html li元素
I have this html li element
<li class="list-group-item ng-scope active" ng-repeat="report in lineageController.reports" ng-click="lineageController.activate(report)" ng-class="{active : lineageController.active == report}">
正如你在class属性中看到的那样,有一个活跃的类。
As you can see inside class attribute there is an active class.
我的问题是我有这个元素,我想根据类属性是否具有其他活动值进行检查,然后使用xpath更优雅的解决方案。
My problem is that I have this element and I want to do a check based on if the class attribute has that "active" value among the others, being more elegant solution then using xpath.
我该怎么做?
推荐答案
鉴于您已找到您的元素,并且您想检查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正确指出的那样,有一种更简单的方法(效果不佳):
EDIT
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
这篇关于如何检查元素是否包含特定的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!