Reputation: 21
How can i compare the list<>of data which i have fetched from backend into my java code to the ui elements by fetching the data of entire div in selenium java ? Please suggest if there is a way i can fetch the text() of all elements from ui div and put into a list other than driver.findelements
Upvotes: 0
Views: 884
Reputation: 8676
You can do it easily with Java stream API. Assume you have the page like this (say you have saved the code to /tmp/texts.html
):
<html>
<head/>
<body>
<div id="root">
<div>text 1</div>
<div>
<div>text 2</div>
<div>text 3</div>
</div>
</div>
</body>
</html>
You now can do the following:
public void testList() {
driver.get("file:///tmp/texts.html");
List<WebElement> webElements = driver
.findElements(
By.xpath("//div[@id='root']//div[not(child::*)]"));
List<String> texts = webElements
.stream()
.map(webElement -> webElement.getText())
.collect(Collectors.toList());
System.out.println(texts);
}
This example demonstrates how you collect texts from the elements with a single stream expression.
P.S. - this [not(child::*)]
part of xpath means we're taking the leaf nodes only.
Upvotes: 0
Reputation: 632
As mentioned in the question you are looking for the alternative to the driver.findElements()
. You can use JavaScript Executor as below to achieve the same.
List<String> lst = new ArrayList<String>();
JavascriptExecutor js = (JavascriptExecutor)driver;
Long length = (Long) js.executeScript("return document.getElementsByClassName('r').length");
for(int i=0; i<length; i++) {
lst.add((String) js.executeScript("return document.getElementsByClassName('r')[arguments[0]].innerText", i).toString().trim());
}
Upvotes: 0
Reputation: 978
You can iterate by for loop and check with your text
following code for java , what I am doing here is open google browser and typing as "TESTING" AND store all results and checking word as "Testing Types" and click that option
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class GooglesearchTests {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.findElement(By.name("q")).sendKeys("Testing");
Thread.sleep(Long.parseLong("1000"));
List<WebElement> LIST = driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']"));
System.out.println(LIST.size());
for (int i = 0; i < LIST.size(); i++)
{
//System.out.println(LIST.get(i).getText());
if (LIST.get(i).getText().contains("testing types"))
{
LIST.get(i).click();
break;
}
}
}
}
Upvotes: 1