FindElement And FindElements In Selenium [Differences]

Ria Dayal

Posted On: January 18, 2022

view count305346 Views

Read time21 Min Read

Finding an element in Selenium can be both interesting and complicated at the same time. If you are not using the correct method for locating an element, it could sometimes be a nightmare. For example, if you have a web element with both ID and Text attributes, ID remains constantly changing, whereas Text remains the same. Using an ID locator to locate web elements can impact all your test cases, and imagine the regression results over a few builds in such cases. This is where the methods findElement and findElements in Selenium can help.


Source

In Selenium, ‘findElement’ and ‘findElements’ are commands used to locate elements within a web page. ‘findElement’ retrieves a single element, while ‘findElements’ returns a list of all matching elements. These commands are essential for interacting with web elements during automated testing.

The findElement method in Selenium can help you enormously while using Selenium locators for finding web elements while performing Selenium automation testing. Let’s see the different implements of findElement in Selenium and the differences between findElement and findElements in Selenium.

Let’s get started!!

How to find an Element in Selenium?

When you start to write your Selenium automation script, interaction with web elements becomes your first vital step because it’s the web elements you play around with within your test script. However, interaction with these web elements can only happen if you identify them using the right approach.

findElement method in Selenium is a command which helps you identify a web element. There are multiple ways that findElement provides to uniquely identify a web element within the web page using web locators in Selenium like ID, Name, Class Name, Link Text, Partial Link Text, Tag, which we will see later in the blog.

For now, let’s see the syntax of using findElement in Selenium. We would be using Selenium with Java for the implementation.

Read More – What is Selenium?

Syntax to find an Element in Selenium

The syntax to find an Element in Selenium is:

As shown in the above syntax, this command accepts the “By” object as the argument and returns a WebElement object. The “By” is a locator or query object and accepts the locator strategy. The Locator Strategy can assume the below values:

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

For example, if you want to use ID as the Locator Strategy to identify any web element, it would look like below.

The Locator Strategy further accepts the Locator Value to identify a web element uniquely.

If there is no matching element within the web page, findElement throws NoSuchElementException.

Let us understand it using an example.

Use Case:

  1. Log in to Selenium Playground offered by LambdaTest.
  2. Try to find a web element that is not present on the screen.

Selenium Playground

LambdaTest is a cloud-based cross browser testing platform that supports Selenium Grid, providing a solution to every obstacle you face while performing Selenium automation testing using your local machine. Selenium testing tools like LambdaTest offer an online Selenium Grid consisting of 3000+ online browsers for you to perform Selenium automation testing effortlessly.

Refer to the below test case for the above scenario:

In the above test case, the checkbox web element is not present on the Selenium Playground main home page, and hence, it will throw NoSuchElementException. Check out the console output in this case.

Console Output:

Now, you must be wondering, what if the locator value returns multiple matching elements? FindElement would return you the first element within the web page which matches the locator value. The next question arises: What if you need all those matching web elements? This is where findElements in Selenium comes into the picture.

Let’s see what findElements has to offer!!

How to find Elements in Selenium?

findElements in Selenium returns you the list of web elements that match the locator value, unlike findElement, which returns only a single web element. If there are no matching elements within the web page, findElements returns an empty list.

Syntax to find Elements in Selenium

The syntax to find Elements in Selenium is:

findElements in Selenium example: If you want to use ID as the Locator Strategy for identifying a list of web elements, it would look something like below:

Similar to the findElement() command, this method also accepts the “By” object as the parameter and returns a list of web elements.

Now, since we have seen findElement and findElements in Selenium example, let’s understand the difference between the findElement and findElements in Selenium Java.

Difference between findElement and findElements in Selenium Java

Now that we read about findElement and findElements, let’s have a quick look at their major differences.

                      findElement

                findElements

Returns the first matching web element within the web page even if multiple web elements match the locator value.

Returns a list of multiple web elements matching the locator value.

Throws NoSuchElementException in case there are no matching elements.

Returns an empty list in case there are no matching elements.

Returns a single web element

Returns a collection of web elements.

No indexing is required since only one element is returned.

Each web element is indexed starting from 0.

Note: The latest version of Selenium is Selenium 4 when writing this article. This Selenium WebDriver Tutorial for beginners and professionals will help you learn what’s new in Selenium 4 (Features and Improvements).

You can follow the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, Cypress testing, CI/CD, and more.

Locator Strategies of findElement and findElements in Selenium Java

Let us now understand the various locator strategies that can be used with findElement and findElements in Selenium Java. We will see their implementation making use of Selenium Playground offered by LambdaTest.

We will also make use of the LambdaTest cloud Selenium Grid to automate our test cases.

Selenium Grid refers to a software testing setup that enables QAs to perform parallel tests across multiple browsers and devices with unique operating systems. When the entire setup of Selenium Grid is accessible using cloud-based servers, it is called Selenium Grid On Cloud. An online Selenium Grid helps you focus on writing better Selenium test scripts rather than worrying about infrastructure maintenance.

Find Element by ID

As we all know, the ID locator in Selenium is one of the widely used locators for locating desired WebElement on a document (or page). If a website uses dynamically generated IDs, this strategy cannot uniquely find an element. However, it will still return the first web element which matches the locator value.

For example, If you have a web element with a tag as Button which has a dynamic ID, where ID is getting changed from ‘ID-3465-text1’ to ‘ID-4434-textE2’, in such cases, it becomes difficult to use the ID attribute. However, if it remains static, you can easily use the ID to locate the Web Element.

Syntax to find Element by ID:

Use Case:

Let us see the checkbox demo page of Selenium Playground and locate the checkbox web element using ID. Further, we will click on the same checkbox and validate the success message.

FindElement And FindElements

Locator:

The correct locator value making use of id in the above case would be

Implementation:

Consider the below test case file.

You can use the below testng.xml file for running the test case.

You can use the below pom.xml file for installing the necessary dependencies.

Code Walkthrough:

Let us now understand the different areas of code in detail.

  1. Imported Dependencies: Here, we have imported all the necessary classes of Selenium WebDriver, WebDriverWait, Desired Capabilities, and RemoteWebDriver to set the respective browser capabilities and run the test cases on the grid.
  2. Imported Dependencies

  3. Global Variables: As we have used a Selenium Grid Cloud like LamdaTest to perform our test execution, we are using the below-shown variables.

Here, you can populate the values for your corresponding username and access key, which can be collected by logging into your LambdaTest Profile Section. You can copy the Username and the Access Token to be used in the code. However, the grid URL will remain the same, as shown below.

We have also used the Listener class here in order to customize the TestNG Report. TestNG provides us with a lot of TestNG Listeners (e.g. IAnnotationTransformer, IReporter, etc). These interfaces are used while performing Selenium cloud testing mainly to generate logs and customize the TestNG reports.

To implement the Listener class, you can simply add an annotation in your test class just above your class name.

Syntax:

3. @BeforeTest(Setup Method): Here, we have used the LambdaTest Desired Capabilities Generator and have set the necessary capabilities of browser name, version, platform, etc., for our Selenium Remote WebDriver. After that, we are opening the website in the launched browser.

4. @Test(findElementById): In this case, we first locate the web element for the checkbox using ID and then click on it. Later, we locate the success message and validate if it appears correctly after clicking on the checkbox.

5. @AfterTest(closeBrowser): Here, we are just closing the launched browser.

Once the tests are completed, you can also view your test results, logs, and the test recording as well in your LambdaTest Automation Dashboard.

Find Element by Name

Name locator in Selenium is similar to find by ID, except the driver will locate an element by the “name” attribute instead of “id”.

Syntax to find Element by Name:

Use Case:

Let us see the input form page of Selenium Playground and write the locator for the input text boxes such as Name, Email, etc.

Locator:

The correct locator value making use of name in the above case would be:

Implementation:

Now, let us automate entering the value of name and email making use of the findElement by Name.

Code Walkthrough:

@Test(findElementByName): In this case, we are first locating the web element for the Name text box and entering a value in the same. Later, we are locating the web element for the Email text box and the entering value in the email text box.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Find Element by ClassName

The ClassName locator in Selenium finds the elements on the web page based on the CLASS attribute value. Here the value of the “class” attribute is passed as the locator.

Syntax to find Element by ClassName:

Use Case:

Let us see the table pagination demo page of Selenium Playground and write the locator for the dropdown to change the number of rows being displayed to 10.

Locator:

The correct locator value making use of ClassName in the above case would be:

Implementation:

Below is the test class file that can be used for implementing the test case.

Code Walkthrough:

@Test(findElementByClassName): In this case, we are first locating the web element for the dropdown using ClassName. Later, we are using Select Class for changing the dropdown value to 10 by using the selectByVisibleText option.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Find Element by TagName

A tagName is a part of a DOM structure where every element on a page is defined via tags like input tag, button tag or anchor tag, etc. Each tag has multiple attributes like ID, name, value class, etc. The TagName locator in Selenium finds the elements on the web page based on the element.

Syntax to find Element by TagName:

Use Case:

Let us see the same table pagination demo page of Selenium Playground and write the locator for the dropdown to change the number of rows displayed using the tag name.

Locator:

The correct locator value making use of tag name in the above case would be:

Implementation:

Below is the test class file that can be used for implementing the test case.

Code Walkthrough:

@Test(findElementByTagName): In this case, we are first locating the web element for the dropdown using TagName. Later, we are using Select Class for changing the dropdown value to 10 by using the selectByVisibleText option.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Find Element by Link Text

The Link Text locator in Selenium is used to identify the hyperlinks on a web page. It is determined with the help of an anchor tag. For creating the hyperlinks on a web page, we can use an anchor tag followed by the link Text.

Accessing links using their exact link text is done through the findElement by Link Text method. However, if two links have the exact link text, this method will only access the first one.

Syntax to find Element by Link Text:

Use Case:

Let us see the radio button demo page of Selenium Playground and write the locator for the Selenium Playground hyperlink, which is used for navigation to the home page as highlighted below.

Locator:

The correct locator value making use of link text in the above case would be

Implementation:

Below is the test class file which can be used for implementing the case.

Code Walkthrough:

@Test(findElementByLinkText): In this case, we are first locating the web element for the navigation link to the main Selenium Playground page using Link Text and later, click on the same.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Find Element by Partial Link Text

Accessing links using a portion of their link text is done using the By.partialLinkText() method. If you specify a partial link text that has multiple matches, only the first match will be accessed.

Syntax to find Element by Partial Link Test:

Use Case:

Let us see the same radio button demo page of Selenium Playground and write the locator for the Selenium Playground hyperlink, which is used for navigating to the home page as highlighted below. However, this time we will make use of the partial link text.

Locator:

The correct locator value making use of link text in the above case would be:

Implementation:

Below is the test class file which can be used for implementing the case.

Code Walkthrough:

@Test(findElementByPartialLinkText): In this case, we are first locating the web element for the navigation link to the main Selenium Playground page using Partial Link Text and later, click on the same.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Find Element by CSS Selector

CSS Selectors are one of the locator strategies used in Selenium to identify the web elements. The CSS Selectors locator in Selenium mainly uses the character sequence pattern, which identifies the web elements based on their HTML structure. Locating an element using a CSS selector in Selenium may seem a little more difficult than using attributes like id, name, link, etc. Still, it’s one of the most efficient strategies to locate dynamic elements that don’t have consistent HTML attributes. CSS Selector syntax is quite similar to the XPath syntax. It can be represented as follows.

Let us now see the syntax of using a CSS selector with the findElement in Selenium.

Syntax to find Element by CSS Selector:

Use Case:

Let us see the single checkbox demo page of Selenium Playground and write the CSS selector for the checkbox, and later use the same in locating the web element using findElement.

Locator:

The correct locator value making use of CSS selector in the above case would be:

Implementation:

Below is the test class file which can be used for implementing the case.

Code Walkthrough:

@Test(findElementByCSSSelector): In this case, we are first locating the web element for the checkbox using CSS selector and then clicking on it. Later, we locate the success message and validate if it appears correctly after clicking on the checkbox.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Find Element by XPath

Also known as XML Path, the XPath locator in Selenium is one of the most commonly used locators in Selenium WebDriver that can help you navigate through the HTML structure of a page.

The basic format of XPath in Selenium is explained below.

Let us now see the syntax of using XPaths with find elements in Selenium.

Syntax to find Elements by XPath:

Use Case to find Element by XPath:

Let us see the same example as we saw in the CSS selector, single checkbox demo page of Selenium Playground, and write the XPath for the checkbox.

Locator:

The correct locator value making use of XPath in the above case would be

Implementation:

Below is the test class file which can be used for implementing the case.

Code Walkthrough:

@Test(findElementByCSSSelector): In this case, we are first locating the web element for the checkbox using XPath and then clicking on it. Later, we locate the success message and validate if it appears correctly after clicking on the checkbox.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Use Case to find Elements by XPath:

Let us see an implementation using findElements as well.

Log in to Selenium Playground and list down all the section headers on the page.

Locator:

When we inspect the section headers using XPath, we see that multiple elements are being returned making use of the same XPath. Hence, in such cases, it would be appropriate to use findElements.

Implementation:

Below is the test class file which can be used for implementing the case.

Code Walkthrough:

@Test(findElementsByXPath): In this case, we are locating the section headers using XPath and storing them in a list of web elements. Later, we iterated through the list and printed their text.

The remaining areas remain the same as we did in the Code Walkthrough of our first example.

Console Output:

Once you run the above test case, your console output would look something like below.

Once the tests are completed, you can also view your test results, logs, and the test recording as well in your LambdaTest Automation Dashboard.

Upon completion of the test, test results will be displayed on the LambdaTest Analytics Dashboard. The dashboard shows all the details and metrics related to your tests.

Navigate to the LambdaTest Analytics Dashboard to view the metrics of your tests. The Test Overview will allow you to quickly assess test performance and overall health. Meanwhile, the Test Summary will show how many passes and fails your team has run and the overall efficacy of these tests.

If you’re a developer who’s looking to take your development and test engineering skills to the next level, this Selenium 101 certification from LambdaTest can help you reach that goal.

Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

Conclusion

In this article on the difference between findElement and findElements in Selenium, we learned about what is findElement and findElements in Selenium Java and had a glance at their major differences. We also saw the various implementations of findElement using ID, Name, ClassName, TagName, etc. In the end, we also implemented a use case using findElements.

Hope you enjoyed reading this article and learned something new about Find Element.

Happy Testing!!

Frequently Asked Questions (FAQs)

What is the return type of findElement and findElements in selenium?

The findElements and findElement functions are used to pinpoint specific elements on a webpage. The findElements function returns a list of WebElements, whereas findElement only returns the first instance of WebElement.

When should we use findElement () and findElements ()?

You can use the findElement command to uniquely identify a (one) web element within the web page. Whereas, findElements command is used to uniquely identify the list of web elements within the web page.

What is difference between quit () and close ()?

The close() method closes the current driver window and releases any resources held. The quit() method exits the application.

How to find elements by id in selenium?

To locate elements by their id in Selenium, use the “find_element_by_id” method, which allows you to identify elements based on their unique identifier. This approach ensures precise targeting of specific elements on a webpage, aiding in effective test automation and web scraping tasks.

How to find elements by class in selenium?

To locate elements by class in Selenium, use the find_elements_by_class_name() method. This allows you to identify elements based on their CSS class. By leveraging this powerful feature, you can efficiently interact with web elements during automated testing and web scraping tasks.

How to find hidden element in selenium webdriver c#?

To locate hidden elements in Selenium WebDriver using C#, you can employ the “FindElement” method along with the “ExpectedConditions” class. By using explicit waits, you can wait for the element to become visible or interactable. This ensures a professional and reliable approach to uncovering hidden elements.

How to click and find elements in Selenium?

In Selenium, clicking and finding elements involves using the WebDriver interface’s methods, such as findElement() and click(). By employing various locating strategies like ID, class name, XPath, or CSS selectors, one can effectively interact with web elements. Automation testers widely utilize these techniques for web testing and navigation.

Author Profile Author Profile Author Profile

Author’s Profile

Ria Dayal

A Senior Quality Engineer By Profession, an automation enthusiast and loves to anchor. Her expertise revolves around Selenium, Java, Rest Assured, and Jenkins. Shell scripting too interests her a lot. Ria enjoys reading novels and writing is her comfort zone.

Blogs: 9



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free