如何检查元素是否包含特定的类属性

时间:2015-09-22 09:14:32

标签: java css selenium selenium-webdriver webdriver

如何检查selenium web元素是否包含特定的css类。

我有这个html li元素

<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属性中看到的那样,有一个活动的类。

我的问题是我有这个元素,我想根据类属性是否具有&#34; active&#34;进行检查。在其他人之间的价值,使用xpath是更优雅的解决方案。

我该怎么做?

9 个答案:

答案 0 :(得分:26)

鉴于您已找到您的元素并且您想要检查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正确指出的那样,有一种更简单的方式(效果不佳):

public boolean elementHasClass(WebElement element, String active) {
    return element.getAttribute("class").contains(active);
}

这种方法看起来更简单,但有一个重要的警告:

正如@JuanMendes所指出的,如果您要搜索的类名是其他类名的子字符串,则会遇到问题:

  

例如class =“test-a test-b”,搜索class.contains(“test”)将返回true但它应该为false

答案 1 :(得分:7)

@drkthng提供的答案有效,但您可能会遇到类名是另一个类名的子集的情况。例如:

<li class="list-group-item ng-scope active">text</li>

如果你想找到班级“项目”,那么提供的答案会给出误报。您可能想尝试这样的事情:

public boolean hasClass(WebElement element, String htmlClass) {
    String classes = element.getAttribute("class").split("\\s+");
    if (classes != null) {
        for (String classAttr: classes) {
            if (classAttr.equals(htmlClass)) {
                return true;
            }
        }
    }
    return false;
}

答案 2 :(得分:1)

Simmilar与前一个,但具有java 8功能:

const joinDate = new Date(obj.date);
let snap = [
    obj.name,
    obj.surename,
    obj.email,
    obj.nip,
    obj.phone,
    obj.adress + " " + obj.home + " " + (obj.local=="brak" ? "" : obj.local),
    obj.city,
    obj.zip,
    obj.spentPoint,
    '',
    ''
];
orders.push(new Promise((resolve) => {
    let userNip = i;
    let ordersRef = firebase.database().ref('/orders/' + userNip);

    ordersRef.once("value", (snapshot) => {
        let ord = snapshot.val();
        let i = 0;

        for(let u in ord) {
            let o = ord[u];
            let newDate = new Date(o.date);
            let formatttedDate = String(newDate.getDate()) + "/" + String(newDate.getMonth()+1) + "/" + String(newDate.getFullYear());
            snap[10+i] = formatttedDate;
            for(let x in o.items) {
                snap[9+i] += String(o.items[x].title) + "[ Punktów: " + o.items[x].summary + " ]";
            }
            i = i + 2;
        }
        resolve();
    })
}));
data.push(snap);

答案 3 :(得分:1)

使用javascript:classList.contains

 WebElement element = By.id("id");
 String className = "hidden";
 JavascriptExecutor js = (JavascriptExecutor) driver;
 Boolean containsClass = js.executeScript("return arguments[0].classList.contains(arguments[1])", element, className);

答案 4 :(得分:1)

改进@ uesports135的答案,“ classess”应为String数组。

 public boolean hasClass(WebElement element, String htmlClass) {
        String[] classes = element.getAttribute("class").split("\\s+");
        if (classes != null) {
            for (String classAttr: classes) {
                if (classAttr.equals(htmlClass)) {
                    return true;
                }
            }
        }
        return false;
    }

答案 5 :(得分:1)

对于任何正在寻找 C# 实现的人:

public static class WebElementExtensions
{
    private static Regex _classNameValidatorRegex = new Regex(@"^[a-z][a-z0-9\-_]*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
    private static Regex _whiteSpaceRegex = new Regex(@"\s+");

    public static bool HasClass(this IWebElement element, params string[] htmlClasses)
    {
        if (!htmlClasses.Any())
            throw new ArgumentException("No html classes to match.");

        if (!htmlClasses.All(c => _classNameValidatorRegex.IsMatch(c)))
            throw new ArgumentException("Invalid CSS class(es) detected.");

        var classAttribute = element.GetAttribute("class");
        if (string.IsNullOrWhiteSpace(classAttribute))
            return false;

        var elementClasses = _whiteSpaceRegex.Split(classAttribute.Trim()).ToHashSet();

        return htmlClasses.All(c => elementClasses.Contains(c));
    }

    public static bool HasAnyClass(this IWebElement element, params string[] htmlClasses)
    {
        if (!htmlClasses.Any())
            throw new ArgumentException("No html classes to match.");

        if (!htmlClasses.All(c => _classNameValidatorRegex.IsMatch(c)))
            throw new ArgumentException("Invalid CSS class(es) detected.");

        var classAttribute = element.GetAttribute("class");
        if (string.IsNullOrWhiteSpace(classAttribute))
            return false;

        var elementClasses = _whiteSpaceRegex.Split(classAttribute.Trim()).ToHashSet();

        return htmlClasses.Any(c => elementClasses.Contains(c));
    }
}

答案 6 :(得分:0)

尝试使用contains();

String classes = divPubli.getAttribute("class");
assertTrue("The element does not contain .maClass class .publi",classes.contains("maClass"));

答案 7 :(得分:0)

基于常见的{classList之前的javascript技术:

public boolean hasClass(WebElement element, String theClass) {
    return (" " + element.getAttribute("class") + " ").contains(" " + theClass + " ");
}

答案 8 :(得分:-1)

您可以使用jquery:

$( "#yourElement" ).hasClass( "protected" )

或这个

$( "#yourElement" ).is( ".pretty.awesome" )

另一个例子

$( "#yourElement" ).is( ":hidden" )

在这里How do I test whether an element has a particular class