首页 > 解决方案 > Selenide:如何从 ElementsCollection 中获取所有活动元素?

问题描述

我正在尝试为集合编写 if 语句,但遇到了问题。例如,以下元素具有li指示该元素是否处于活动状态的标记:

<dl class="p-property-item">
<dt class="p-item-title" data-spm-anchor-id="42e07cb3WzvrLA">Color:</dt>
    <dd class="p-item-main">
        <ul id="j-sku-list-3" class="sku-attr-list util-clearfix" data-sku-prop-id="14" data-sku-show-type="none" data-isselect="true" data-spm-anchor-id="2114.10010108.1000016/B.i3.42e07cb3WzvrLA">
               <li class="active">
                    <a data-role="sku" data-sku-id="29" id="sku-2-29" href="javascript:void(0)" data-spm-anchor-id="2114.10010108">
                        <span data-spm-anchor-id="42e07cb3WzvrLA">White</span>
                    </a>
               </li>
        </ul>
                    <div data-role="msg-error" class="msg-error sku-msg-error" style="display: none;">
                        Please select a Color
                    </div>
    </dd>

我从页面中获取所有元素并将其放入集合中:

@FindBy(how = How.CSS, using = "#j-product-info-sku > dl:nth-child(2) > dd > ul > li > a > span")
private ElementsCollection colorList;

public ElementsCollection getColor() { return colorList; }

但我不知道如何从集合中获取具有 "active" 的元素li。我的意思是,如何获取所有活动元素,是否有任何选项可以识别它们?

注意:所有元素都是可见的,因此与按可见选项过滤无关。

我还使用了这里提到的 java 方法:Filtering an ElementsCollection

    public static Condition hasChildWithCondition(final By locator, final Condition condition) {
    return new Condition("hasChildWithCondition") {
        public boolean apply(WebElement element) {
            return element.findElements(locator).stream().
                    filter(child -> condition.apply(child)).count() > 0;
        }

        public String toString() {
            return this.name;
        }
    };
}



Condition hasChild = hasChildWithCondition(By.cssSelector("li"), Condition.text("active"));

if ((page.getColor().size() != 0) && (page.getColor().filterBy(hasChild))){
            //to do
        }

但就我而言,我收到一个错误:Operator && cannot be applied to 'boolean','com.codeborne.selenide.ElementsCollection'

标签: javaseleniumselenium-webdriverselenide

解决方案


解决方案找到了:为了只将活动元素放入集合中,我决定忽略li“禁用”类的元素

ElementsCollection colorList = $$("#j-product-info-sku > .p-property-item > .p-item-main > ul > li:not(.disabled) > a");

截至目前,该集合仅包含活动元素


推荐阅读