TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: FindElement and FindElements Commands
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

FindElement and FindElements Commands

Last updated: Mar 03, 2024 12:12 pm
By Harsh S.
Share
10 Min Read
findElement and findElements Commands and Examples
findElement and findElements Commands and Examples.
SHARE

Whenever you plan to automate any web application using Webdriver, you usually start by finding the HTML elements on the page. Then, you choose the right strategy to locate them. Webdriver defines two methods for identifying the elements; they are findElement and findElements.

Contents
1- Find locators using Firefox’s Inspector and FirePath Tool.2- The difference between findElement and findElements methods.findElement() method.findElements() method.Code Example3- Understand multiple ‘By’ strategies to access locators3.1- By ID3.2- By Name3.3- By Class Name3.4- By TagName3.5- By LinkText or PartialLinkText3.6- By CSS selector3.7- By XPath

How to Use FindElement and FindElements

We have given many examples of the above Webdriver commands in our previous blog posts. Now, you’ll see a detailed overview of both these methods.

Next, we’ll also help you explore the different locator strategies that you can use along with these methods. Here is the list of topics we are covering today.

1- Find locators using Firefox’s Inspector and FirePath Tool.

Let’s first see an animated GIF to demonstrate Firefox’s Inspector and FirePath Tool, and then we’ll review the key differences between the findElement and findElements methods.

We’ve captured a small set of actions to showcase how can you use Firefox’s internal inspector tool to find a unique locator. Then there is the FilePath add-on demo to determine or verify the XPath of any element.

findElement and findElements Demo
Firefox Inspector and FirePath Demo.

2- The difference between findElement and findElements methods.

findElement() method.

  • You can use this command to access any single element on the web page.
  • It returns the object of the first matching element of the specified locator.
  • It throws a NoSuchElementException exception when it fails to find the element.
  • Its syntax is as follows.
WebElement user = driver.findElement(By.id("User"));

findElements() method.

  • First of all, we don’t use it frequently as its usage is very limited.
  • It gives back the whole list of all the elements matching the specified locator.
  • If the element doesn’t exist or is not available on the page then, the return value will be an empty list.
  • Its syntax is as follows.
List<WebElement> linklist = driver.findElements(By.xpath("//table/tr"));

Code Example

Now let us provide a straight and practical example of these methods to give you a clear picture.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class findElementTest {

	public static void main(String[] args) throws Exception {

		// Start browser
		WebDriver driver = new FirefoxDriver();

		// Maximize the window

		driver.manage().window().maximize();

		// Navigate to the URL

		driver.get("https://techbeamers.com");

		// Sleep for 5 seconds

		Thread.sleep(5000);

		// Here, see how the XPath will select unique Element.
		WebElement link = driver
				.findElement(By.xpath("'//table/tr[1]/td[1]/a"));

		// click on the link
		link.click();
	}
}
import java.util.Iterator;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class findElementsTest {

	public static void main(String[] args) throws Exception {

		// Launch browser
		WebDriver driver = new FirefoxDriver();

		// Maximize window
		driver.manage().window().maximize();

		// Navigate to the URL
		driver.get("https://techbeamers.com");

		// Sleep for 5 seconds
		Thread.sleep(5000);

		// Here, the code below will select all rows matching the given XPath.

		List<WebElement> rows = driver.findElements(By.xpath("//table/tr"));

		// print the total number of elements
		System.out.println("Total selected rows are " + rows.size());

		// Now using Iterator we will iterate all elements
		Iterator<WebElement> iter = rows.iterator();

		// this will check whether list has some element or not
		while (iter.hasNext()) {

			// Iterate one by one
			WebElement item = iter.next();

			// get the text
			String label = item.getText();

			// print the text
			System.out.println("Row label is " + label);
		}
	}
}

3- Understand multiple ‘By’ strategies to access locators

Webdriver references the Web elements by using the findElement(By.<locator()>) method. The findElement method uses a locator/query object known as <“By”>. There are various kinds of “By” strategies that you can utilize depending on your requirements. Let’s go through them one by one.

3.1- By ID

Command: By.id(<element ID>)

According to this strategy, the By method will return the first element matching the id attribute value. If it doesn’t find any matching element then, it’ll raise a NoSuchElementException. Using an element ID is the most preferred way to locate an element, as usually, IDs have unique values.

However, in a large project that is in the development phase, the developers may use non-unique IDs or auto-generating IDs. Ideally, they should avoid the occurrence of any of these conditions.

Example:

<input id="TechBeamers">
// Java example code to find the input element by id.

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

3.2- By Name

Command: By.name(<element-name>)

By.Name() is another useful way to locate an element but it is also prone to same the issue as we’d seen with the ID. The issue was what if the web developer could’ve used non-unique/auto-generated names on a page.

This strategy states that the <By.Name()> method will return the first element matching the name attribute. If it’s not able to locate it then, it’ll throw a NoSuchElementException.

Example:

<input name="TechBeamers">
// Java example code to find the input element by name.

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

3.3- By Class Name

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

This method gives you the element which matches the values specified in the “class” attribute. If the element has more than one class, then this method will match against each one of them.

Example:

<input class="TechBeamers">
// Java example code to find the input element by className.

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

3.4- By TagName

Command: By.tagName(<html tag name>)

You can use this method to find the elements matching the specified tag name. You may call this method when you want to extract the content within a tag or wish to perform any action on the tag element.

Example:

<form action="viewuser.asp" method="get" id="userform">
    Name: <input type="text" name="name"><br>
     Age: <input type="text" name="age"><br>
</form>
<button type="submit" form="userform" value="Submit">Submit</button>
WebElement form = driver.findElement(By.tagName("button"));

// You can now perform any action on the form button.
form.submit();

3.5- By LinkText or PartialLinkText

Commands: By.linkText(<link text>) and
                       By.partialLinkText(<link text>)

Using this method, you can track the elements of “a” tags (Link) with the link or partial-link names. Apply this method, when you have the link text that appears within the anchor tag.

Example:

<a href="#test1">TechBeamers-1</a>
<a href="#test2">TechBeamers-2</a>
// Java example code to find element matching the link or partial link text.
WebElement link = driver.findElement(By.linkText("TechBeamers-1"));
assertEquals("#test1", link.getAttribute("href"));

// Or
WebElement link = driver.findElement(By.partialLinkText("TechBeamers-2"));
assertEquals("#test2", link.getAttribute("href"));

3.6- By CSS selector

Command: By.cssSelector(<css-selector>)

With this method, you can use a CSS selector to locate the element. The CSS is a cascading style sheet; it sets the styles for a web page and its elements.

Example:

<input class="email" id="email" type="text" placeholder="your@email.com">
<input class="btn btn-small" type="submit" value="Subscribe to our blog">
// Java code example for using cssSelector.

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

//Or

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

WebElement subscribe = driver.findElement(By.cssSelector("input[type='submit'][value='Subscribe to our blog']"));

Apart from the above examples, you can also perform partial matching on HTML attributes.

	
1) ^= as in input[id^='Tech'] means Starting with the given string.
 

2) $= as in input[id$='_Beamers'] means Ending with the given text.
 

3) *= as in Input[id*='techbeamers'] means Containing the given value.

3.7- By XPath

Command: By.xpath(<xpath>)

You can try this method when you want to locate an element using the XPath query. XPath is a way to traverse through the document object model and gives you the ability to select specific elements, attributes, or a section of an XML document.

Example:

// Java code example 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[5]"));

// Finding elements using attributes values.
WebElement item = driver.findElement(By.xpath("img[@alt='banner']"));

// XPath starts-with() example.
// => input[starts-with(@id,'User')]

// XPath ends-with() example.
// => input[ends-with(@id,'_name')]

// XPath contains() example.
// => input[contains(@id,'email')]

The Usage of findElement and findElements

We came out with this post because we wanted you to know the nitty-gritty of the findElement and findElements methods. Another concept we addressed was to choose between the different By.locator() strategies. You can master these concepts only by practicing with real-time web applications. Here is a post where you’ll see a lot of demo websites to practice Webdriver commands.

We expect you to apply this knowledge while you work and create better automation solutions.

Best,

TechBeamers.

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Selenium Webdriver Commands Essential for Test Automation Learn Basic Selenium Webdriver Commands
Next Article Checkbox and Radio Button Operations In Webdriver Handle Checkbox & Radio Button in Webdriver

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x