findElement and findElements in Selenium

Explore Find Elements in Selenium with methods like findElement and findElements in Selenium to locate Web Elements using multiple locators.

Get Started free
Guide Banner Image
Home Guide findElement and findElements in Selenium

findElement and findElements in Selenium

Finding elements on the webpage can be a nightmare due to the complexity of web elements. However, web elements play a vital role in developing and testing any application. Different actions can be performed to find elements in Selenium using commands like search elements, associate events with web elements, etc.

To make things easier for testers, this article will offer insights into Selenium findElement vs findElements with the help of an example.

Introduction to Selenium Find Element

Interaction with a web page requires the driver to locate a web element, and either trigger a JavaScript event like a click, enter, select, etc. or type in the field value. Usually, one starts automated testing of any web app by finding relevant web elements on the web page. Such automated testing is often executed using frameworks like Selenium WebDriver.

Selenium defines two methods for identifying web elements:

  • findElement: A command to uniquely identify a web element within the web page.
  • findElements: A command to identify a list of web elements within the web page.

Let’s understand the difference between these two methods in greater detail.

Difference between findElement vs findElements in Selenium

findElementfindElements
Returns the first matching web element if the locator discovers multiple web elementsReturns a list of multiple matching web elements
Throws NoSuchElementException if the element is not foundReturns an empty list if no matching element is found
Detects a unique web elementReturns a collection of matching elements

Now that you’ve understood the core difference between Selenium findElement vs findElements, also try to get into some fundamental Selenium commands with Basic Commands of Selenium Webdriver.

Find Element in Selenium command Syntax (with explanation)

The findElement command returns an object of the type WebElement. It can use various locator strategies such as ID, Name, ClassName, link text, XPath, etc.

Below is the syntax:

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

Locator Strategy comprises the following values:

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

Locator Value is the unique method to identify the web element quickly.

Example: Find Element in Selenium:

driver.findElement(By.xpath("//input[@id='gh-ac']")).sendKeys("Guitar");

Find Elements in Selenium command Syntax (with explanation)

The findElements command returns an empty list if no elements are found using the given locator strategy and locator value.

Below is the syntax of findElements command

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

Example: Find Elements in Selenium

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

Now, let’s delve deeper into understanding how to find web elements with the help of various locators. One can refer to different types of locators in Selenium.

How to use Selenium findElement

1. Find by ID

ID is uniquely defined for each element and is the most common way to locate elements using ID Locator. If a website has dynamically generated ids, then this strategy cannot be used to find an element uniquely. However, it will return the first web element which matches the locator.

Example: Let’s take bstackDemo for automating and finding the elements. When we open the website, there is one link button “Favourites”, as shown below.

Find elements in Selenium - findelement id

As you can see, it comprises an ID locator whose value is favourites.

The code snippet for find element in Selenium uses the same locator value to write a program:

from selenium import webdriver

from selenium.webdriver.chrome.service import service

from selenium.webdriver.chrome.options import Options

service = Service("path/to/driver")

options = Options()

driver = webdriver.Chrome(service=service, options=options)





#instance of Chrome | Firefox | IE driver

driver.get(https://bstackdemo.com/)




elementID = driver.findElement(By.id("favourites"))

# will raise NoSuchElementException if not found

2. Find by Name

This is similar to Find By ID, except the driver will locate an element by the “name” attribute instead of “id”.

Example: Consider the same bstackdemo webpage. After successful login, we have one field with name viewport value shown as the given image.

find element in Selenium By NameThe entire code remains similar to that of ID locator, except that the difference will be in the findElement syntax.

elementName = driver.findElement(By.name("viewport"))

3. Find By LinkText

LinkText helps find links in a webpage. It is the most efficient way of finding web elements containing links.

When the tester hits that link and inspects it, it locates the link text Returns, as shown in the snapshot below.

Find Element in Selenium - LinkText

This can be located simply by using Selenium findElement with the syntax below:

elementLinktext = driver.findElement(By.linkText(“Offers”))

4. Find By CSS Selector

CSS Selector is used to provide style rules for web pages and can identify one or more web elements.

Example: Consider the website’s homepage; there is an”Add to cart” button for all products. Using the same value, the Find elements in Selenium method can locate the element.

elementcss= driver.findElement(By.cssSelector('div[id='1'] div[class='shelf-item__buy-btn']'))

5. Find By XPath

XPath is a Selenium technique to navigate through a page’s HTML structure. XPath enables testers to navigate through the XML structure of any document and can be used on both HTML and XML documents.

Example: Let’s try to locate the favorites button on the homepage with the help of XPath. The code below shows that it contains an ID locator. Note that relative XPath starts with ‘//’.

In the image below, one can see a Hyperlink tag. Start with //a. Here //a  implies a tag name. Use the id attribute and pass favourites in single quotes as its value.

This will give the XPath expression shown below:

//a[@id=’favourites’]

Find By XPATH in Selenium

Now, using the Selenium findElement method, execute the code below:

elementxpath = driver.findElement(By.xpath("//a[@id=’favourites’]"))

Run Selenium Tests on Real Device Cloud

Locating web elements is the basis of automated Selenium testing of websites and web apps. To learn more about the fundamentals of Selenium, don’t forget to look at Selenium WebDriver Tutorial and what’s new with Selenium Grid 4.

findElement and findElements in Selenium

Tags
Automation Testing Selenium Webdriver