Tutorials  /  JavaScript

Selenium findElement and findElements Examples

Ccentron Redaktion · February 2024 ·5 min read ·JavaScript, 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

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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

Code
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:

Code
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

Code
List elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));

Example:

Code
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

Go
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

Go
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>

Java example code to find the input element by id:

Code
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:

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

3. By Class Name

Command: driver.findElement(By.className(<element-class>))

Example: <input>

Java example code to find the input element by className:

Code
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:

Code
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 type="text" placeholder="xxx@email.com"> <input type="submit" value="Subscribe to blog>

Java example code to find element matching link or partial link text:

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

6. By XPath

Command: driver.findElement(By.xpath(<xpath>))

Java example code for XPath:

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

Selenium findElement and findElements Examples

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren