过滤ElementsCollection
我正在尝试创建一个过滤ElementsCollection
的函数,在每个元素的子ElementsCollection
上使用条件而不是元素本身。
这就是我想出的:
public static ElementsCollection filterByChild(ElementsCollection elementsCollection, String childCssSelector, Condition condition) { Predicate 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") { public boolean apply(WebElement element) { return element.findElements(locator).stream(). filter(child -> condition.apply(child)).count() > 0; } public String toString() { return this.name } }; }
然后用它来过滤:
ElementsCollection collection = $$(".parent"); Condition hasChild = hasChildWithCondition(By.cssSelector("a"), Condition.text("http://www.link.com")); collection.filterBy(hasChild);