• Selenium Video Tutorials

Selenium WebDriver - Finders



Selenium Webdriver can be used to locate elements having the same matching locator value. On a web page, if multiple elements are having the same locator value, only the reference to the first matching element (from the right upper corner of the page) is obtained.

findElement Method

The findElement() method return the first element having the same locator value in the DOM. In case, there are multiple elements having the same locator values, we can identify a single element using the id locator since it always uniquely identifies an element on a web page.

Identify Element using the Nested findElement

Let us take an example of an HTML code snippet as highlighted in the below image having the elements with the same tagname as li. Let us identify the first li element(with parent element with tagname ul) having a child element link(with tagname ‘a’) as Text Box

Selenium Finders 1

To get hold of that element, we first uniquely identified the element that is an ancestor to the searched element and not the ancestor of the undesired element, and then applied the findElement() method on that object.

We can get all the matching elements having the same locator values with the help of the findElements() method. This returns a list of matched elements. In case, there is no matching element, we would get a list with size 0.

Syntax with nested command −

WebDriver driver = new ChromeDriver();

// identify all elements under tagname ul
WebElement elements = driver.findElement(By.id("navMenus"));

// identify first li element under ul then click
WebElement element = elements.findElement(By.xpath("//li[1]/a"));

Example 1

Let us click on the Text Box link, and get the text Text Box on the web page.

Selenium Finders 2

Code Implementation

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

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

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage      
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // identify element then click
      WebElement l = driver.findElement(By.xpath("//*[@id='headingOne']/button"));
      l.click();

      // identify all elements under tagname ul
      WebElement elements = driver.findElement(By.id("navMenus"));

      // identify first li element under ul then click
      WebElement element = elements.findElement(By.xpath("//li[1]/a"));
      element.click();

      WebElement e = driver.findElement(By.xpath("//*[@id='TextForm']/h1"));
      System.out.println("Text is: " + e.getText());

      // Closing browser
      driver.quit();
   }
}

Output

Text is: Text Box

In the above example, we had first identified the element with nested locators and then obtained the text with the message in the console: Text is: Text Box.

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

However, we can use an optimized technique to identify that element using xpath or css locator, since the nested approach would not be good with respect to the performance.

Syntax

WebDriver driver = new ChromeDriver();

// identify element with xpath
WebElement element = driver.findElement(By.xpath("//*[@id='navMenus']/li[1]/a"));

Example 2

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

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

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // identify element then click
      WebElement l = driver.findElement(By.xpath("//*[@id='headingOne']/button"));
      l.click();

      // identify element with xpath
      WebElement element = driver.findElement(By.xpath("//*[@id='navMenus']/li[1]/a"));
      element.click();

      WebElement e = driver.findElement(By.xpath("//*[@id='TextForm']/h1"));
      System.out.println("Text is: " + e.getText());

      // Closing browser
      driver.quit();
   }
}

Output

Text is: Text Box

In the above example, we had first identified the element with xpath locator and then obtained the text with the message in the console: Text is: Text Box.

Identify Links Using the findElements Method

The links are identified by the anchor tagname with an attribute called href.

Let us now discuss the identification of link - Bad Request on a webpage shown in the below image. First, right click on the page, then click on the Inspect button in the Chrome browser. Then, the corresponding HTML code for the whole page would be visible. For inspecting a link on a page, click on the left upward arrow, available to the top of the HTML code as highlighted below.

Selenium Finders 3

Once, we had clicked and pointed the arrow to the Bad Request hyperlink, its HTML code was visible,reflecting both the anchor tagname(referred to as ‘a’ and enclosed in <>), and href the attribute.

Selenium Finders 4

Let us take an example of the above page, where we would first count the total number of links using the findElements() method, then we would click on a specific link, say the Bad Request. After clicking on that link, we would get the message Link has responded with status 400 and status text Bad Request.

Selenium Finders 5

Syntax

WebDriver driver = new ChromeDriver();
List<WebElement> totalLnks = driver.findElements(By.tagName("a") );

Example

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class TotalLnks {
   public static void main(String[] args) throws InterruptedException {
   
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver() ;

      // adding implicit wait of 10 secs
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // Opening the webpage where we will count the links
      driver.get("https://www.tutorialspoint.com/selenium/practice/links.php" ) ;

      // Retrieve all links using locator By.tagName and storing in List
      List<WebElement> totalLnks = driver.findElements(By.tagName("a") );
      System.out.println( "Total number of links: " + totalLnks.size() ) ;

      // Running loop through list of web elements
      for( int j = 0; j < totalLnks.size(); j ++){
         if( totalLnks.get(j).getText().equalsIgnoreCase("Bad Request") ) {
            totalLnks.get(j).click() ;
            break ;
         }
      }
	  
      // get text
      WebElement t = driver.findElement
         (By.xpath("/html/body/main/div/div/div[2]/div[4]"));
      System.out.println("Text is: " + t.getText());

      // Closing browser
      driver.quit();
   }
}

Output

Total number of links: 42
Text is: Link has responded with status 400 and status text Bad Request

In the above example, we had counted the total number of links on a web page, and received the messages in the console - Total number of links: 42 and then obtained the text generated after performing the the click with the message - Text is: Link has responded with status 400 and status text Bad Request.

findElements Method with No Matching Element

Let us take an example and implement a code where we would see that the list returned by the findElements() method may contain 0 element, if there is 0 element with the given locator value.

Example

package org.example;

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;
import java.util.concurrent.TimeUnit;

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

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will identify element
      driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");

      // Retrieve all elements using By.class name ul and storing in List
      List<WebElement> total = driver.findElements(By.tagName("input"));
      System.out.println( "Total number of elements with tagname input: " + total.size() ) ;

      //Closing browser
      driver.quit();
   }
}

Output

Total number of elements with tagname input: 0

In the above example, we counted all the elements having tagname as input received the messages in the console - Total number of elements with tagname input: 0(since there is no matching element).

findElement Method with No Matching Element

Let us take an example and implement a code where we would get a NoSuchElement exception, returned by the findElement() method, if there is 0 element with the given locator value.

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

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

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will identify element
      driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");

      // Retrieve element using By.class name ul
      WebElement e = driver.findElement(By.className("ul"));
      System.out.println( "Element is : " + e);

      // Closing browser
      driver.quit();
   }
}

Output

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: 
   Unable to locate element: {"method":"css selector","selector":".ul"}
   (Session info: chrome=121.0.6167.160)
For documentation on this error, please visit:
https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

Process finished with exit code 1

In the above example, we had received Process finished with exit code 1 signifying unsuccessful execution of the code. Also, we had got the NoSuchElementException(as there is no element on the web page, having the matching locator value).

Difference between findElements and findElement Method

Thus the basic difference between the findElement() and findElements() are listed below −

  • The findElement() method returns a web element, while the findElements() method returns the list of web elements.

  • In case there is no matching element, the findElement() method will throw NoSuchElementException while the findElements() method will return a list with size 0.

activeElement Method

Of all the elements on the web page, we can get the element which is on focus using the activeElement() method.

Let us take an example of the above page, where we would first enter the text Selenium in the input box with the help of the sendKeys() method. Then get the attribute of the element in focus using the activeElement() method(done after switching context of the driver to the element in focus).

Selenium Finders 6

Example

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class HandlingActivesElement {
   public static void main(String[] args) throws InterruptedException {
   
      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();
      
      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
      
      // launching URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
      
      // Identify the input box with xpath locator
      WebElement e = driver.findElement(By.xpath("//*[@id='fullname']"));
      
      // enter text in input box
      e.sendKeys("Selenium");
      
      // Get the value of element in focus after switching driver context
      String a = driver.switchTo().activeElement().getAttribute("value");
      System.out.println("Value entered: " + a);
      
      // Closing browser
      driver.quit();
   }
}

Output

Value entered: Selenium

In the above example, we had first entered the text Selenium in the input box, and also retrieved the value of the current element in focus in the console with the message - Value entered: Selenium(which is the value entered).

Conclusion

This concludes our comprehensive take on the tutorial on Selenium Webdriver Finders. We’ve started with describing findElement method, identify element using the nested findElement, identify links using the findElements method, findElements method with no matching element, findElement method with no matching element, differences between findElements and findElement method, activeElement Method, and examples to illustrate how to use finders in Selenium Webdriver. This equips you with in-depth knowledge of the Selenium Webdriver Finders. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.

Advertisements