4

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);
}
4
  • What exactly shall the code print? Your code works fine - it prints the WebElement object itself, which is just a kind of handle to the element in a remote web browser. Do you want to print its HTML code? Or its text body? Commented Nov 28, 2017 at 13:38
  • Oh, and by the way - your XPath seems to be invalid, at least in your example here. You should use an XPath matching all child elements, not the parent element (something with /div or /* at the end) Commented Nov 28, 2017 at 13:40
  • I want to loop through all the elements in the container_class and to find the elements background color. So, if any of the elements color is blue then click it. Commented Nov 28, 2017 at 14:20
  • @SarabuSandeep Use getCssValue("background-color"). Commented Nov 28, 2017 at 14:55

1 Answer 1

3

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());  
 }
Sign up to request clarification or add additional context in comments.

2 Comments

It would be more efficient to use a CSS selector, #container_id > div. You can get the inner DIVs in a single locator instead of having to scrape the page twice. Remove the first line and replace the second line with List<WebElement> links = driver.findElements(By.cssSelector("#container_id > div"));
@JeffC Thanks. I know that but i post the two step code just to understand the hierarchical steps to get specific element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.