我希望使用和了解谓词和 Lambda 表达式。特别是与 Selenium 一起使用。
假设您有大量 WebElements 选择(列表),并且您想要对其应用谓词过滤器以使列表变小。
对于下面的 1、2、3,我需要进行哪些更改,我是否走在正确的轨道上?
List<WebElement> webElements = driver.findElements(By.cssSelector(".someClassName")); // returns large list
// then try and filter down the list
Predicate<WebElement> hasRedClass -> Predicate.getAttribute("class").contains("red-background");
Predicate<WebElement> hasDataToggleAttr -> Predicate.getAttribute("data-toggle").size() > 0;
// without predicate probably looks like this
//driver.findElements(By.cssSelector(".someClassName .red-background"));
// 1. this is what I think it should look like???
List<WebElement> webElementsWithClass = webElements.filter(hasRedClass);
// 2. with hasDataToggleAttr
List<WebElement> webElementsWithDataToggleAttr = webElements.filter(hasDataToggleAttr);
// 3. with both of them together...
List<WebElement> webElementsWithBothPredicates = webElements.filter(hasRedClass, hasDataToggleAttr);
最佳答案
我希望这就是您正在寻找的内容:
List<WebElement> webElements = driver.findElements(By.cssSelector(".someClassName")); // returns large list
// then try and filter down the list
Predicate<WebElement> hasRedClass = we -> we.getAttribute("class").contains("red-background");
Predicate<WebElement> hasDataToggleAttr = we -> we.getAttribute("data-toggle").length() > 0;
// without predicate probably looks like this
//driver.findElements(By.cssSelector(".someClassName .red-background"));
// 1. this is what I think it should look like???
List<WebElement> webElementsWithClass = webElements.stream()
.filter(hasRedClass).collect(Collectors.toList());
// 2. with hasDataToggleAttr
List<WebElement> webElementsWithDataToggleAttr = webElements.stream()
.filter(hasDataToggleAttr).collect(Collectors.toList());
// 3. with both of them together...
List<WebElement> webElementsWithBothPredicates = webElements.stream()
.filter(hasDataToggleAttr.and(hasRedClass)).collect(Collectors.toList());
关于java - 带谓词的 Selenium 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174546/