简体   繁体   中英

How to convert webelement into List<Webelement> in java

I have webelement

WebElement element = driver.findelement(By.cssSelector("div#name"))

I want to convert WebElement element into list

How can i convert it into list

I dont want to declare findelements again to get list. I need to reuse the webelement(element)

只需将行更改为下面,我们使用.findElements()将返回元素列表而不是.findElement()

List<WebElement> elements = driver.findelements(By.cssSelector("div#name"));

You can use java.util.Collections.singletonList.

And your code can be so:

WebElement element = driver.findelement(By.cssSelector("div#name"));
List<WebElement> elements = java.util.Collections.singletonList(element );

Java is a statically typed , so to before putting the WebElement into the list, you have to create the list first and then add the WebElement within the list and you can use the following solution:

List<WebElement> elements = new ArrayList<>();
elements.add(driver.findElement(By.cssSelector("div#name")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM