• 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.

The findElement() method would 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.

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 make an attempt to 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 would first uniquely identify the element that is an ancestor to the searched element and not the ancestor of the undesired element, and then apply the findElement() method on that object.

We would also be able to 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

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"));

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

Selenium Finders 2

Example

Code Implementation on Finders.java class file.

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

Process finished with exit code 0

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

Code Implementation with xpath on Finder.java class file.

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

Process finished with exit code 0

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.

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

In HTML terminology, every link(referred to as hyperlinks) are identified by the tagname called anchor. Also, each link on a webpage has an attribute called href.

Let us now discuss the identification of anchor tags for hyperlink - Bad Request on a webpage shown in the below image. First, we would need to right click on the webpage, and then click on the Inspect button in the Chrome browser. Then, the corresponding HTML code for the whole page would be visible. For investigating a single element on a page, we would need to click on the left upward arrow, available to the top of the visible 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, both reflecting the anchor tagname(referred to as ‘a’ and enclosed in <>), and href attribute containing the link to the page.

Selenium Finders 4
<a href="javascript:void(0)" id="bad-request" onclick="shide('brequest')">Bad Request</a>

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 text Link has responded with status 400 and status text Bad Request.

Selenium Finders 5

Syntax

Syntax with findElements() method −

WebDriver driver = new ChromeDriver();
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 ;
   }
}

Example

Code Implementation on TotalLnks.java class file.

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

Process finished with exit code 0

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.

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

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

Code Implementation on FindElement.java class file.

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

Process finished with exit code 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).

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

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

Code Implementation on FindElementWithException.java class file.

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).

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.

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

Syntax

Webdriver driver = new ChromeDriver();
driver.findElement(By.xpath("value of xpath")).sendKeys("value entered"); 
String a = driver.switchTo().activeElement().getAttribute("value");

Example

Code Implementation on HandlingActivesElement.java class file.

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

Process finished with exit code 0

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).

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

Thus, in this tutorial, we had discussed how to use various finders to find web elements on a web page using the Selenium Webdriver.

Advertisements