简体   繁体   English

Java | 硒| 使用Stream从Weblement列表中返回单个Webelement

[英]Java | Selenium | Using Stream to return single Webelement from a list of weblements

I'm trying to filter a list of webelements down to a single webelement by the elements's innerText. 我正在尝试通过元素的innerText将一个webelements列表过滤到单个webelement。 In c#, I would use a linq where clause. 在C#中,我将使用linq where子句。 In Java, I'm trying to use stream but I can't figure out why I'm getting the incompatible type error (required: org.openQA.selenium.Webelement. Found: java.util.optional) 在Java中,我尝试使用流,但无法弄清楚为什么出现不兼容的类型错误(必需:org.openQA.selenium.Webelement。找到:java.util.optional)

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;
}

The error is fair. 该错误是公平的。 findFirst returns an Optional . findFirst返回Optional You have to get the object explicitly like so. 您必须像这样显式地获取对象。

WebElement correct = emp.stream().filter((element) -> element.getText().contains(correctName)).findFirst().orElse(null);

So if the Optional is not empty, it will return the value, otherwise it will return null . 因此,如果Optional不为空,它将返回该值,否则将返回null Note get on an Optional is not recommended to use and it'll be deprecated in future. 请注意,不建议您在Optional上使用get ,它会在以后被弃用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用列表设置类似的weblement <webelement> 硒中 - Setting up similar weblements using a list<webelement> in selenium webelement 列表中的一些 wblements 值变为空白如何等待 webelement 的每个值出现在 selenium 中的 webelements 中 - some of the value of weblements in list of webelement are coming blank How to wait for each value of webelement to appear in webelements in selenium Selenium Java-无法填充列表 <WebElement> 从表 - Selenium Java - Cant fill List<WebElement> from Table 使用Java中的Stream从forEach返回列表 - Return List from forEach using Stream in java 如何放置清单 <webelement> 使用硒网络驱动程序/ Java进入ArrayList? - How to put List<webelement> into ArrayList using selenium web driver/java? java.lang.ClassCastException:无法转换为 org.openqa.selenium.WebElement 使用 executeScript() 从 shadowHost 返回 shadowRoot - java.lang.ClassCastException: cannot be cast to org.openqa.selenium.WebElement using executeScript() to return shadowRoot from shadowHost 选择列表WebElement的子级-Java-Selenium WebDriver - Select child of List WebElement - Java - Selenium WebDriver Java Selenium Webdriver手动填充列表WebElement - Java Selenium webdriver filling list webelement manually 在Java中使用Selenium从下拉列表中选择随机WebElement - Choosing random WebElement from drop down using Selenium with Java 如何使用带有Java的Selenium WebDriver将鼠标悬停在Web元素上 - How to mouseover on a webelement using Selenium WebDriver with Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM