过滤 ElementsCollection

Filtering an ElementsCollection

我正在尝试创建一个函数来过滤 ElementsCollection,条件是每个元素的子元素而不是元素本身。

这是我想出的:

 public static ElementsCollection filterByChild(ElementsCollection elementsCollection, String childCssSelector,
        Condition condition) {

        Predicate<SelenideElement> childHasConditionPredicate = element -> element.$(childCssSelector).has(condition);
        elementsCollection.removeIf(childHasConditionPredicate);
        return elementsCollection;
    }

像这样调用这个函数时:

myCollection = SelenideHelpers.filterByChild(myCollection, "a", Condition.text("http://www.link.com");

我收到以下错误消息:

java.lang.UnsupportedOperationException: Cannot remove elements from web page

我没有找到关于此错误消息的任何相关信息可应用于我的代码。我想知道为什么会出现这条信息。

检查 SelenideElementIterator 是如何设计的:

@Override
public void remove() {
  throw new UnsupportedOperationException("Cannot remove elements from web page");
}

要使其正常工作,您需要创建自定义条件,例如:

import com.codeborne.selenide.Condition;
import com.codeborne.selenide.ElementsCollection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import static com.codeborne.selenide.Selenide.$$;


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

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

然后用它来过滤:

ElementsCollection collection = $$(".parent");
Condition hasChild = hasChildWithCondition(By.cssSelector("a"), Condition.text("http://www.link.com"));
collection.filterBy(hasChild);