Skip to content

Selenium

Overview

We are aware that a webpage consists of numerous WebElements such as text boxes, buttons, lists, etc. We can perform a variety of actions on these WebElements using Selenium commands like search elements, associate events with web elements, etc. To perform these actions we first need to interact with a web page so that we can use WebElement Commands/actions. In this topic, we will discuss the different methods used to find an element on the webpage using Selenium so that we can perform actions on these elements. We will cover the following topics in this article.

Find elements using Selenium WebDriver? Why do we need to find a web element in Selenium? How to find elements in Selenium? What is By class in Selenium? Difference between find Element and find Elements in Selenium. Find elements using Selenium WebDriver? As mentioned above to interact with WebElements, we first have to find or locate these elements on the webpage. We can find elements on a web page by specifying the attributes such as Id of the element or class name of the element and such other parameters. These alternatives using which we can find elements on a webpage are called locator strategies.

The following are the locator strategies we can use while locating the elements.

Locator Description id finds elements by ID attribute. The search value given should match the ID attribute. name Finds or Locates elements based on the NAME attribute. The name attribute is used to match the search value. class name Finds elements that match the class name specified. Note that compound classes are not allowed as strategy names. tag name Finds or Locates elements having tag names that match the search value. CSS selector Matches CSS selector to find the element. XPath Matches XPath expression to the search value and based on that the element is located. link text Here the visible text whose anchor elements are to be found is matched with the search value. partial link text Here also we match the visible text with the search value and find the anchor value. If we are matching multiple elements, only the first entry will be selected. Now before moving to how we can use these various types of locators to locate the elements, let's first understand why exactly there is a need to find the elements in Selenium?

How to find elements in Selenium? As discussed, Selenium WebDriver provides two methods using which we can find an element or list of elements on a web page. These are:

findElement(): This method uniquely finds a web element on the web page.

findElements(): This method finds a list of web elements on the web page.

Let's understand the usage and details of these methods in the following sections:

findElement() in Selenium The findElement() method of the Selenium WebDriver finds a unique web element within the webpage.

It’s syntax looks like below:

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

Soure Reference