Finding Child Elements in WebDriver using findElements

Finding Child Elements in WebDriver using findElements is like a cakewalk for many. But I am pretty sure it might have perturbed you when you might have encountered this thought for the very first time. So let’s start our journey to find child element with step by step example on google home page. Note:  Code of this google home page might change in future but the concept will remain the same. So read this page carefully.

So here is the scenario

1- First Search a string in google search
2- Print all the result coming as search result.

IT Certification Category (English)728x90

So here are two approaches to achieve this

First approach :

Finding generic Xpath and fetching all element in a list using findElements method and then iterating in the list and printing all the search result using getText() method…

So let’s see how to achieve this generic XPath

1- Open Google.com
2- Search “I want child Element”
3- Right-click on the first search result and select inspect element. Screen something like this would be rendered
Right Click and Inspect Element4- Now right click on greyed out html code and Select Copy Xpath and paste it somewhere in notepad or it you want then in any text editor.
Like xpath for first element that i get is : //*[@id="rso"]/div[2]/div[1]/div/h3/a
5- Again go to second search result text and follow the step 3 and 4 and fetch the second xpath and xpath for second search result is : //*[@id="rso"]/div[2]/div[2]/div/h3/a
6- In the same fashion xpath for third search result would be : //*[@id="rso"]/div[2]/div[3]/div/h3/a

7- Find the similarity in xpath and also find html tag where some index/pattern is changing with each search result.
8- So what we got similar in all xpath <here i am going to divide the complete xpath in static and dynamic element>
So static parts are
a)//*[@id=”rso”]/div[2]/
b)+/div/h3/a
and dynamic html tag is div[1], div[2], div[3] in between both static parts i.e. a) and b)
9- So remove the index of div that is varying each time.
So our xpath would be : //*[@id='rso']/div[2]/div/div/h3/a
Note: here we need to replace double quote.
10- So now we have a generic xpath and now we can write the code that could print all the search result one after another
so here is the code that would print all the search result

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/*
* @author : Dwarika
*/
public class PrintAllSearchResult {

public static void main(String[] args) throws InterruptedException {

WebDriver driver = new ChromeDriver();
driver.get("http://google.co.in");
driver.findElement(By.name("q")).sendKeys("I want child Element");
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
//here we would use findElement since we have generic xpath for more than one webelements
List list = driver.findElements(By.xpath("//*[@id='rso']/div[2]/div/div/h3/a"));

for(WebElement element:list)
{

System.out.println(element.getText());

}
}
}

Result in console

div without blur child element - Stack Overflow
css - Display HTML child element when parent element is ...
Have child element fill rest of parent element? - Stack Overflow
[Solved] I Want To Get Third Child Element 'Executiontype ...
Non-Transparent Elements Inside Transparent Elements ...
The Difference Between :nth-child and :nth-of-type | CSS ...
Selecting Elements – You Don't Need jQuery! – Free ...
overflow a child element outside a parent - WordPress
XML & Related Technologies - Page 247 - Google Books Result
Getting the count of child elements who match a certain ...

Second Approach:  


This approach is going to take help of Selenium WebDriver Javadocs of WebElement. We would first take all the parents elements in a list and then will iterate element of the list and will find the child on the basis of generic XPath for child

But before going ahead please read this part of Javadocs for FindElements

java.util.List<WebElement> findElements(By by)
Find all elements within the current context using the given mechanism. When using xpath be aware that webdriver follows standard conventions: a search prefixed with “//” will search the entire document, not just the children of this current node. Use “.//” to limit your search to the children of this WebElement. This method is affected by the ‘implicit wait’ times in force at the time of execution. When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.
So let’s see how to achieve this one:
1- Search the string in the google search textbox
2- Press F12, developer tool should get rendered, Now go to magnify icon in developer tool and inspect the sub-container of the search results page that contains all the search results. Our search would end once we get the result as belowFindElements
3- Further drill down and find another container that is going to have all the search result text..and like this
FindElements
4- If we would further drill down then we would come to know that class=’rc’ is coming with each search result container.
5- So take it as pivot element as a parent and fetch it in List using finElements(By.className("rc"))
6- Iterate in the list and now figure out the generic HTML tag that has been used for search result text and concatenate findElement method with each element of each iteration.
so here are two way
a) Xpath: In this scenario, h3 is a tag that is being used for search result text
so XPath would be : //h3 <since we are inside smallest container>
Now here is one tricky thing that we need to note is to use “.” just before XPath inside to let the control know that only h3 with recent iteration element is being in use otherwise it will take the first element each time and would print first search result for alliteration. so to avoid this scenario code would look like this
element.findElement(By.xpath(".//h3")).getText();

b) if we are going to use any of other locator methods then code would be like this
element.findElement(By.tagName("h3")).getText(); here element is iterated element
So lets see one code that would print all the text but here it will go first to parent and then it would go to child element.

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/*
 * @author: Dwarika
 */
public class FindingChild {
    
    public static void main(String[] args) throws InterruptedException {
        
        WebDriver driver = new ChromeDriver();
        driver.get("http://google.co.in");
        driver.findElement(By.name("q")).sendKeys("customizing surefire reports");
        driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
        Thread.sleep(5000);
        
        List list = driver.findElements(By.className("rc"));
        
        System.out.println("List"+list);
        for(WebElement element:list)
        {
        
        System.out.println(element.findElement(By.xpath(".//h3")).getText());
            //System.out.println(element.findElement(By.tagName("h3")).getText());
        
        }
        
        //link.click();
        Thread.sleep(10000);
        
        driver.quit();
    }

}

if you like this post then please share, like and comment.

Dwarika Dhish Mishra

My name is Dwarika Dhish Mishra, its just my name and I am trying to bring the worth of my name in to actions and wants to be the solution not the problem. I believe in spreading knowledge and happiness. More over I am fun loving person and like travelling a lot. By nature I am a tester and a solution maker. I believe in the tag line of http://ted.org “Idea worth spreading” . For the same, I have created this blog to bring more and more learning to tester fraternity through day to day learning in professional and personal life. All contents are the part of my learning and so are available for all..So please spread the contents as much as you can at your end so that it could reach to every needful people in testing fraternity. I am pretty happy that more and more people are showing interest to become the part your Abode QA blog and I think this is good sign for us all because more and more content would be before you to read and to cherish. You may write or call me at my Email id: dwarika1987@gmail.com Cell: 9999978609

You may also like...

5 Responses

  1. hema says:

    Generic Xpath you’ve used in the post is not working.

    • Yes, recently google has made changes in its html structure so some of the xpath would not be working but after this post i am pretty sure you would be able to write these generic xpath at your own.

      Thanks

  2. this helped a lot thank you!

  3. Vahan Hovhannisyan says:

    This helped find my bug. Thank you!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.