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.
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