java - 带谓词的 Selenium 过滤器

标签 java selenium lambda java-8 predicate

我希望使用和了解谓词和 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/

相关文章:

java - 如何确定测试是在本地运行还是在远程服务器上运行

python - 在字符串切片中使用比较运算符

Java计算器(运算顺序)

java - 避免代码重复——最好的方法

java - 不显示对话框

javascript - 防止 React 组件不必要的重新渲染

loops - 在Scheme中编写While循环

java - JFreeChart 从另一个 JDialog 接收方程产生 "AWT-EventQueue-0"java.lang.NullPointerException

node.js - 使用 Nightwatch.js 页面对象

java - 类型错误 : Cannot find function createHTMLDocument in object