我正在尝试通过元素的内部文本将网络元素列表过滤为单个网络元素。在 C# 中,我会使用 linq where 子句。在Java中,我尝试使用流,但我不明白为什么会出现不兼容类型错误(必需:org.openQA.selenium.Webelement。找到:java.util.可选)
public List <WebElement> emp = driver.findElements(By.className("employee"));
public String correctName = driver.findElement(By.id("name")).getText();
public WebElement getName(){
WebElement correct = emp.stream().filter((element) -> element.getText().contains(correctName)).findFirst();
return correct;
}
最佳答案
这个错误是公平的。 findFirst
返回一个Optional
。您必须像这样显式获取对象。
WebElement correct = emp.stream().filter((element) -> element.getText().contains(correctName)).findFirst().orElse(null);
所以如果Optional
不为空,就会返回该值,否则返回null
。请注意,不建议使用 Optional
上的 get
,并且将来会弃用它。
关于 java | Selenium |使用 Stream 从 Web 元素列表中返回单个 Web 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49279685/