Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through each element in a div using Selenium Java?

I am trying to loop through all the elements in a div. How can I do it?

Till now I have tried like below but its not working. I expect it has to print all the elements in the container_class but its printing like this "[[[FirefoxDriver: firefox on XP (d3434gfe-d431-4e51-e6rt-a3asewc7806f)] -> xpath: id("divs_container_class")]]"

I want to print all the elements, what am I doing wrong?

HTML:

<div class="container_class" id="container_id">
    <div id="1" class="1 class"></div>
    <div id="2" class="2 class"></div>
    <div id="3" class="3 class"></div>
    <div id="4" class="4 class"></div>
</div>

Java(Selenium):

List<WebElement> elementsxpath = driver.findElements(By.xpath("id(\"divs_container_class\")"));
for(int i=0; i<elementsxpath .size(); i++) {
    System.out.println(elementsxpath);
}
like image 964
Sarabu Sandeep Avatar asked Sep 17 '25 04:09

Sarabu Sandeep


1 Answers

If the html body you posted is valid you can try with the below code.

 List<WebElement> elements = driver.findElements(By.cssSelector("#container_id > div"));
 for (WebElement element : elements) {
    System.out.println(element.getText());  
 }
like image 126
Mahmud Riad Avatar answered Sep 18 '25 17:09

Mahmud Riad