Tutorial

Selenium findElement and findElements Examples

Published on August 3, 2022
Default avatar

By Meghna Gangwar

Selenium findElement and findElements Examples

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Whenever you want to interact with a web page, we require a user to locate the web elements. We usually start by finding the HTML elements on the page whenever we plan to automate any web application using WebDriver. Selenium WebDriver defines two methods for identifying the elements, they are findElement and findElements.

  1. findElement: This command is used to uniquely identify a web element within the web page.
  2. findElements: This command is used to uniquely identify the list of web elements within the web page.

There are multiple ways to uniquely identify a web element within the web page such as ID, Name, Class Name, LinkText, PartialLinkText, TagName, and XPath.

Difference between findElement and findElements Methods

FindElement() Method:

  • This command is used to access any single element on the web page
  • It will return the object of the first matching element of the specified locator
  • It will throw NoSuchElementException when it fails to identify the element

FindElements() Method:

  • This command is used to uniquely identify the list of web elements within the web page.
  • The usage of this method is very limited
  • If the element doesn’t exist on the page then, then it will return value with an empty list

Selenium findElement Command

Find Element command takes in the By object as a parameter and returns an object of type WebElement. By object can be used with various locator strategies such as ID, Name, ClassName, link text, XPath, etc.

Syntax of FindElement command

WebElement elementName = driver.findElement(By.LocatorStrategy("LocatorValue"));

Locator Strategy can be any of the following values.

  • ID
  • Name
  • Class Name
  • Tag Name
  • Link Text
  • Partial Link Text
  • XPath

Locator Value is the unique value using which we can identify the web element. It is the core responsibility of developers and testers to make ensure that web elements are uniquely identified by using certain properties such as ID or Name. Example:

WebElement login= driver.findElement(By.linkText("Login"));

Selenium findElements Command

Selenium findElements command takes in By object as the parameter and returns a list of web elements. It returns an empty list if no elements found using the given locator strategy and locator value.

Syntax of FindElements command

List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));

Example:

List<WebElement> listOfElements = driver.findElements(By.xpath("//div"));

How to use Selenium findElement Command

The following application is used for demo purpose: https://www.irctc.co.in/nget/user-registration Scenario

  1. Open the https://www.irctc.co.in/nget/user-registration for AUT
  2. Find and click radio button
package com.journaldev.selenium.findelement;

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

public class SeleniumFindElement { 
       public static void main (String [] args){ 

     System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
     WebDriver driver= new ChromeDriver();
     driver.manage().window.maximize():
     driver.get(:"https://www.irctc.co.in/nget/user-registration");

//Find the radio button for "Male" by using ID and click on it
driver.findElement(By.id("M")).click();

       } 
}

How to use Selenium findElements Command

The following application is used for demo purpose https://www.irctc.co.in/nget/user-registration Scenario

  1. Open the https://www.irctc.co.in/nget/user-registration for AUT
  2. Find the text of radio buttons and print on console

package com.journaldev.selenium.findelements;

import java.util.List;

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

public class SeleniumFindElements {

	public static void main(String[] args) {

	System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
	WebDriver driver= new ChromeDriver();
        driver.get("https://www.irctc.co.in/nget/user-registration");
        List<WebElement> elements = driver.findElements(By.id("M"));
        System.out.println("Number of elements:" +elements.size());

       for(int i=0; i<elements.size(); i++){
       System.out.println("Radio button text:" + elements.get(i).getAttribute("value"));
	}
     }
}

Multiple By Strategies To Access Selenium Locators

Selenium Webdriver references the web elements by using findElement(By.) method. The findElement method uses a locator object known as <"By">. There are various kinds of “By” strategies which you can use depending on your requirement.

1. By ID

Command: driver.findElement(By.id(<element ID>)) Example: <input id=“JournalDev”> Java example code to find the input element by id

WebElement user = driver.findElement(By.id("JournalDev"));

2. By Name

Command: driver.findElement(By.name(<element-name>)) Example: <input name=“JournalDev”> Java example code to find the input element by name

WebElement user = driver.findElement(By.name("JournalDev"));

3. By Class Name

Command: driver.findElement(By.className(<element-class>)) Example: <input class=“JournalDev”> Java example code to find the input element by className.

WebElement user = driver.findElement(By.className("JournalDev"));

4. By LinkText

Command: driver.findElement(By.linkText(<link text>)) Example: <a href=“#test1”>JournalDev-1</a> <a href=“#test2”>JournalDev-2</a> Java example code to find element matching link or partial link text:

WebElement link = driver.findElement(By.linkText("JournalDev-1"));
WebElement link = driver.findElement(By.partialLinkText("JournalDev-2"));

5. By CssSelector

Command: driver.findElement(By.cssSelector(<css-selector>)) Example: <input class=“email” id=“email” type=“text” placeholder=“xxx@email.com”> <input class=“btn btn-small” type=“submit” value="Subscribe to blog> Java example code to find element matching link or partial link text:

WebElement emailText = driver.findElement(By.cssSelector("input#email"));

6. By XPath

Command: driver.findElement(By.xpath(<xpath>)) Java example code for XPath:

// Absolute path
WebElement item = driver.findElement(By.xpath("html/head/body/table/tr/td"));

// Relative path
WebElement item = driver.findElement(By.xpath("//input"));

// Finding elements using indexes
WebElement item = driver.findElement(By.xpath("//input[2]"));
```****

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Meghna Gangwar

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel