Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Selenium findElement and findElements Examples

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 elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));

Example:

List 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

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

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

Start Your Cloud Journey Today with Our Free Trial!

Dive into the world of cloud computing with our exclusive free trial offer. Experience the power, flexibility, and scalability of our cloud solutions firsthand.

Try for free!