简体   繁体   English

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

[英]How to check if element contains specific class attribute

How can I check if a selenium web element contains a specific css class.如何检查 selenium web 元素是否包含特定的 css 类。

I have this html li element我有这个 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}">

As you can see inside class attribute there is an active class.正如您在 class 属性中看到的那样,有一个活动类。

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 属性是否具有“active”值进行检查,这是比使用 xpath 更优雅的解决方案。

How can I do this?我怎样才能做到这一点?

Given you already found your element AND you want to check for a certain class inside the class-attribute:鉴于您已经找到了您的元素,并且您想检查 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;
}

#EDIT As @aurelius rightly pointed out, there is an even simpler way (that doesn't work very well): #EDIT 正如@aurelius 正确指出的那样,还有一种更简单的方法(效果不佳):

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

This approach looks simpler but has one big caveat:这种方法看起来更简单,但有一个很大的警告:

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:正如@JuanMendes 所指出的,如果您要搜索的类名是其他类名的子字符串,则会遇到问题:

for example class="test-a test-b", searching for class.contains("test") will return true but it should be false例如 class="test-a test-b",搜索 class.contains("test") 将返回 true 但它应该是 false

#EDIT 2 Try combining the two code snippets: #EDIT 2 尝试组合两个代码片段:

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

That should fix your caveat.那应该可以解决您的警告。

The answer provided by @drkthng works but you might have a case where the class name is a subset of another class name. @drkthng 提供的答案有效,但您可能会遇到类名是另一个类名的子集的情况。 For example:例如:

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

If you wanted to find the class "item" then the provided answer would give a false positive.如果您想找到“项目”类,那么提供的答案将给出误报。 You might want to try something like this:你可能想尝试这样的事情:

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;
}

Use javascript: classList.contains使用 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);

Based on a common pre- classList javascript technique:基于常见的 pre- classList javascript 技术:

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

Simmilar to previous one, but with java 8 capabilities:与上一个类似,但具有 java 8 功能:

String classes= getDriver().findElement(someSelector).getAttribute("class");
Optional<String> classFindResult = Arrays.stream(elementClasses.split(" ")).filter(el -> el.equals("myClass")).findFirst();
if(openClassFindResult.isPresent()){
    return true;
}
return false;

Improving on @uesports135 answer, "classess" should be a String array.改进@uesports135 答案,“classess”应该是一个字符串数组。

 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;
    }

For anyone looking for a C# implementation:对于任何寻找 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));
    }
}

Try using contains();尝试使用 contains();

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

you can use jquery: 您可以使用jquery:

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

or this 或这个

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

another example 另一个例子

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

see here How do I test whether an element has a particular class 请参阅此处如何测试元素是否具有特定的类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM