Filtering an ElementsCollection

故事扮演 提交于 2019-12-20 02:58:20

问题


I'm trying to create a function to filter an ElementsCollection, with a condition on a child of each element instead of the element itself.

Here's what I came up with:

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

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

When calling this function like this:

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

I'm getting the following error message:

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

I did not found any relevant informations on this error message that could be applied to my code. I would like to know why is this message appearing.


回答1:


Check how SelenideElementIterator is designed:

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

To make it work you need to create your custom condition like:

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") {
        public boolean apply(WebElement element) {
            return element.findElements(locator).stream().
                    filter(child -> condition.apply(child)).count() > 0;
        }

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

and then use it to filter:

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


来源:https://stackoverflow.com/questions/47261998/filtering-an-elementscollection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!