Using Contains, Sibling, Ancestor to Find Element in Selenium

In this chapter, we are going to discuss new functions known as Sibling, Contains and Ancestor to Find Element in Selenium for our test script. These functions are present in XPath 1.0 library. XPath along with the combination of these new functions, we can locate any complex web element from the web page. Let’s understand these functions one by one in detail.

Find Element in Selenium Using Contains

By using ‘contains’ function, we can extract a list of web elements which contain the matching text throughout the web page. Following is the syntax to use ‘contains’ function within the XPath.

List<WebElement> elements = driver.findElements(By.xpath("//h1[contains(text(),'Be great at what you do')]/parent::form//h2"));

Let’s understand this better with the help of the following example. Here, we are loading a linked website sign up page and with the help of XPath and the ‘contains’ function, we are going to print the text “Get started – it’s free” on the console as shown below circled in blue.

Find Element in Selenium

Following is the test script to achieve the task that we just discussed.

package seleniumpackage;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class UsingContainsAndSibling {
 public static void main(String args[]) {
  WebDriver driver = new FirefoxDriver();
  driver.get("https://www.linkedin.com/");
  List <WebElement> elements = driver.findElements(By.xpath("//h1[contains(text(),'Be great at what you do')]/parent::form//h2"));
  for (WebElement webElement: elements) {
   System.out.println(webElement.getText());
  }
  driver.quit();
 }
}
Find Element in Selenium

Explanation of the test script

  • Firstly, we are invoking the Firefox driver and going to load the LinkedIn sign up page.
  • By using the ‘findElement’ method of the WebDriver class, we are locating a list of web elements where we are passing the XPath criteria as an argument to this method.
  • XPath criteria suggest locating a web element with a tag as ‘h1’ that contains text as ‘Be great at what you do’. With the help of this tag, we are locating the parent element which is ‘form’ tag. We can use this ‘form’ to locate the following ‘h2’ tag web element.
  • After locating the ‘h2’ tag element, we are fetching the text and print that text on the console.
  • Console shows the text as ‘Get started – it’s free.’

Find Element in Selenium Using Sibling

We can use the ‘sibling’ function to fetch a web element that is a sibling to the parent web element or in other words, if we know the parent element then we can locate a web element that can use the sibling attribute of the XPath. Following is the syntax to use ‘sibling’ function within the XPath.

//SIBLING Demonstration 
List<WebElement> sibElements = driver.findElements(By.xpath("//a[contains(text()," + "'Inside div block 2.')]/parent::div//following-sibling::div[@class='c']//a"));

Find Element in Selenium Using Ancestor

We can use the ‘ancestor’ function to fetch a web element that is an ancestor to the current web element or in other words, if we know the parent element then we can locate a web element that can use the ancestor attribute of the XPath. Following is the syntax to use ‘ancestor’ function within the XPath.

//ANCESTOR Demonstration
List<WebElement> ancElements = driver.findElements(By.xpath("//a[contains(text(),'Inside div block 2.')]/ancestor::div//a"));

In the following example, we are demonstrating the use of a parent, sibling and ancestor function that could be used in collaboration with XPath to find a list of web element. Following is the HTML code to demonstrate the use of these functions.

<html>
   <head>
      <title>Form elements Demo by Selenium Webdriver</title>
   </head>
   <body>
      <form>
      <header> This is header. </header>
      <div class="a">
         <a href="">Inside div block 1.</a> 
         <div class="b">
            <a href="">Inside div block 2.</a> 
            <div class="c"> <a href="">Inside div block 3.</a> </div>
         </div>
      </div>
      <footer> This is Footer. </footer>
   </body>
</html>

Explanation of the HTML Code

In the above HTML code, we have defined three nested div blocks with the class as a, b and c respectively. Each of div block encloses a hyperlink and defined as ‘Inside div block 1.’, ‘Inside div block 2’ and ‘Inside div block 3’ depending on the div block area it is enclosed in. Place this HTML code in the C such that it can be accessed with URL (file:///C:/selenium_demo/Contain-Sibling-Ancestor.html).

Following is the test script in Java to demonstrate contain, parent, sibling and ancestor functions in collaboration with XPath locator.

Explanation of the test script

  • To begin with, we are invoking the Firefox driver after instantiating WebDriver API class ‘FirefoxDriver’.
  • Next, we are using the WebDriver object to invoke and load the URL under test (here file:///C:/selenium_demo/Contain-Sibling-Ancestor.html).
  • Now, we are using the ‘findElement’ method of the WebDriver class to a list of web elements. Here, we are passing the XPath criteria as an argument to this method.
  • Firstly, we are demonstrating the XPath criteria where we have used ‘contains’, ‘parent’ and ‘sibling’ functions as shown below. From this criteria, we are fetching a hyperlink web element that contains text as ‘Inside div block 2.’ when found, we are locating the parent element which is nothing but the 2nd div block tag. We know that the following sibling of 2nd div block is 3rd div block. Therefore, we are using ‘following-sibling’ function that has class as ‘c’ and thereby selecting the hyperlink with a tag as ‘a’. This particular web element is recorded in the list which has a reference as ‘sibElements’.
//SIBLING Demonstration
List<WebElement> sibElements = driver.findElements(By.xpath("//a[contains(text()," + "'Inside div block 2.')]/parent::div//following-sibling::div[@class='c']//a"));
  • In the next step, we are traversing the list elements for ‘sibElements’ in a ‘for’ loop to print the text value of all the element. In this case, since there was a single web element that satisfies the criteria and has text value as ‘Inside div block 3.’ Therefore, it gets printed on the console.
  • Secondly, we are demonstrating the XPath criteria where we have used ‘contains’ and ‘ancestor’ functions as shown below. From this criteria, we are fetching a hyperlink web element that contains text as ‘Inside div block 2.’ when found we are locating the web element with a tag as ‘a’. Obviously, we may observe that there are three such tags found in each of the three nested div blocks. All of these three web elements as tag ‘a’ will be returned to the list of Web Elements that has the reference as ‘ancElements’.
//ANCESTOR Demonstration
List<WebElement> ancElements = driver.findElements(By.xpath("//a[contains(text(),'Inside div block 2.')]/ancestor::div//a"));
  • In the next step, we are traversing the list elements for ‘ancElements’ in a ‘for’ loop to print the text value of all the element. In this case, since there were three web element that satisfies the criteria and have text values as ‘Inside div block 1.’, ‘Inside div block 2.’ and ‘Inside div block 3.’ Therefore, all of these three values will get printed on the console as shown below.
  • Lastly, we will close the current Firefox driver session after using the ‘quit’ method of WebDriver class.

Output

Find Element in Selenium

Following is the output that could be observed once we run the above test script.

Download Code: Using Contains, Sibling, Ancestor to Find Element in Selenium

Conclusion:

In this chapter, we have learned about the Contains, Sibling, Ancestor and parent functions that are present in XPath 1.0 library which helps in locating the complex web elements present on a web page.


Free Selenium Training Course


If you are not a regular reader of this website then highly recommends you Sign up for our free email newsletter!! Sign up just providing your email address below:

Enter your email address:

 

Check email in your inbox for confirmation to get latest updates Software Testing for free.

Happy Testing!!!

Leave a Comment

Share This Post