During web automation testing, it is essential to locate web elements, as this can help save time and effort. Selenium web driver is a perfect tool for this task, offering various ways to locate and work with web elements. In this article, we will explore how to find web elements using Selenium and different types of locators and provide some examples.
Table of contents
- What is a locator in Selenium?
- Types of locators in Selenium
- Finding web elements using Selenium locators
- Difference between findElement and findElements
- Interacting with web elements in Selenium
- Conclusion
What is a locator in Selenium?
A locator in Selenium is an identifier used to find and interact with web elements on a page, such as buttons, checkboxes, and input fields. It helps Selenium Webdriver locate an element in the HTML page structure to perform actions like clicking a button, filling out a form, or selecting an option from a drop-down menu. Once a locator finds a web element, Selenium can perform the respective automation tasks.
Types of locators in Selenium
ID
The ID locator uses an element’s unique ID attribute in the HTML document to locate it within the web page. This locator is one of the most efficient methods for element identification, as IDs are unique for each element on the page. It is also very quick to locate a single, specific element.
The following code shows how to locate a username field by ID:
WebElement usernameField = driver.findElement(By.id("username"));
Code language: Java (java)
Selenium supports multiple programming languages, and the examples we will see here will be in Java, one of the most popular languages in Selenium.
Name
The name locator identifies elements using the name attribute. This method is effective when the name is unique to the element. However, it can be less helpful if multiple elements have the same name. Name can be used for form fields such as email addresses or usernames, where each field has a specific name attribute.
WebElement emailField = driver.findElement(By.name("email"));
Code language: JavaScript (javascript)
Class Name
The class name locator uses the class property of an HTML element to identify it. This locator is helpful when elements share the same styling or functionality. However, if multiple elements have the same class name, this method will return more than one element. You can use class name when elements share the same look or role on a webpage, like buttons or sections with the same design or purpose.
WebElement loginBox = driver.findElement(By.className("login-box"));Code language: JavaScript (javascript)
CSS Selector
The CSS selector locator identifies elements using dynamic CSS syntax. It can find elements based on their characteristics (like class, ID, type, name, value, etc.) or how they are structured in the HTML document. CSS selectors let users locate elements even when the page structure is complex. The CSS selector connects an element selector and a selector value that can locate particular elements on a web page.
WebElement passwordField = driver.findElement(By.cssSelector("#password"));Code language: JavaScript (javascript)
XPath
XPath(XML Path Language) is a language used to search through an XML document and to find web elements on a page. The XPath locator works by navigating the structure of a web page to find elements based on their attributes, text content, or position in the document. It is a powerful tool that can navigate the HTML structure of a webpage, especially useful when other locators such as ID or class fail to find the elements.
WebElement usernameField = driver.findElement(By.xpath("//input[@name='username']"));Code language: JavaScript (javascript)
Avoid using an absolute XPath. An absolute XPath is a full path that begins from the root element and traces the hierarchy to the target element. Let’s look at an example.
Assuming we have this HTML structure:
<html>
<body>
<div>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</body>
</html>Code language: HTML, XML (xml)
An absolute XPath for the Contact element would look like this:
/html/body/div/ul/li[3]/a
Absolute XPaths are brittle: If any part of the DOM changes, such as an additional element being added or removed from the hierarchy, the absolute XPath might break. Therefore, it’s usually better to use relative XPaths or other locating strategies (like By.id() or By.className()) when possible.
Tag Name
The Tag name locator identifies elements by their HTML tag type. This locator is mainly helpful for selecting multiple elements of the same type, such as all button tags, input tags, or div tags. Tag name can be used to locate common elements like headings, paragraphs, or buttons, where the tag type is uniform across the page.
WebElement submitButton = driver.findElement(By.tagName("button"));Code language: JavaScript (javascript)
LinkText
The LinkText locator uses the text in hyperlinks to locate the web element. This is mainly helpful when automating the testing of navigation links and for scenarios where the link text is unique on the page, such as in a navigation bar or footer.
WebElement loginLink = driver.findElement(By.linkText("Login"));Code language: JavaScript (javascript)
Partial LinkText
The Partial LinkText locator uses a part of the text in hyperlinks to locate the web element. This is helpful when only a part of the link text is known or when the text changes dynamically. This locator is not as precise as LinkText but can be helpful when dealing with dynamic content or lengthy link texts.
WebElement signupLink = driver.findElement(By.partialLinkText("sign"));Code language: JavaScript (javascript)
Relative locators
Relative locators are also available in Selenium 4, allowing you to find elements based on their position relative to other elements on the page. Unlike Selenium 3, which needs multiple findElement commands to locate elements based on their surrounding context, relative locators offer a better approach to element identification.
Types of relative locators include:
- above(): Finds an element just above a specified element
- below(): Finds an element just below a specified element
- toLeftOf(): Finds an element to the left of a specified element
- toRightOf(): Finds an element to the right of a specified element
- near(): Finds an element that is near a specified element
WebElement usernameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
WebElement passwordLabel = driver.findElement(RelativeLocator.with(By.tagName("label")).below(usernameField));Code language: JavaScript (javascript)
Finding web elements using Selenium locators
Here, we will use IntelliJ IDEA with Selenium Java dependency to locate the web elements on the OrangeHRM login page (an open source site) using a couple of locators.
How to inspect a web page to find locators
Open your favorite browser and go to the login page for OrangeHRM.
To find locators, we need to inspect the HTML of the target web page. To do this, right-click on any element (e.g., username field, password field, login button, or forgotten password link) in our browser and select the Inspect option.
For the username field, look for:
<name="username">Code language: HTML, XML (xml)
For the password field, look for:
<name="password" type="password">Code language: HTML, XML (xml)
For the login button, look for:
<type="submit" class="oxd-button oxd-button--medium oxd-button--main orangehrm-login-button">Code language: JavaScript (javascript)
For the forgot password link, look for:
<class="oxd-text oxd-text--p orangehrm-login-forgot-header">Code language: JavaScript (javascript)
When creating our Selenium WebDriver test, we’ll use locators such as name for username/password fields, css selector for the Login button and class name for the forgot password link.
Project setup in IntelliJ
Before proceeding, please install IntelliJ IDEA, set up your Java environment variables, and configure Maven on your system.
Open IntelliJ and create a new project by clicking File > New > Project.
On the left side, make sure to select Java. Add a name for your project, choose your project location, and select Maven as the build system. Also, select the appropriate Java version and click the Create button.
After the creation of the project, the pom.xml file will open by default.
For the successful test execution, we need to add the selenium-java and webdrivermanager dependencies to our pom.xml file.
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.15.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.6.2</version>
</dependency>
</dependencies>Code language: HTML, XML (xml)
Be sure to use the latest versions of Selenium and WebDriverManager.
Right-click on the Java folder in the left-hand project structure and click on New > Package.
Then, right-click the newly created package and select New > Java Class. Give your class a name (without spaces) and press Enter.
Create a test script
package your_package_name;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class MyClass {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.get("https://opensource-demo.orangehrmlive.com/");
WebElement usernameField = wait.until(d -> d.findElement(By.name("username")));
WebElement passwordField = wait.until(d -> d.findElement(By.name("password")));
WebElement loginButton = wait.until(d -> d.findElement(By.cssSelector("button.orangehrm-login-button")));
WebElement forgotPasswordLink = wait.until(d -> d.findElement(By.className("orangehrm-login-forgot-header")));
System.out.println("Username field found: " + usernameField.isDisplayed());
System.out.println("Password field found: " + passwordField.isDisplayed());
System.out.println("Login button found: " + loginButton.isDisplayed());
System.out.println("Forgot password link found: " + forgotPasswordLink.isDisplayed());
usernameField.sendKeys("Admin");
passwordField.sendKeys("admin123");
loginButton.click();
wait.until(ExpectedConditions.urlContains("dashboard"));
System.out.println("Logged in successfully. Current URL: " + driver.getCurrentUrl());
} finally {
driver.quit();
}
}
}Code language: JavaScript (javascript)
To run the test, right-click on your test class file in the left side and select Run ‘class_name.main()’ option.
After that, ChromeDriver will be set up automatically using WebDriverManager. It will then open the OrangeHRM login page and find the elements using the specified locators.
Finally, it will print whether each element was found.
Difference between findElement and findElements
In Selenium, findElement and findElements are commands used to locate elements within a web page. The findElement method is useful for locating and interacting with individual web elements. Meanwhile, findElements is useful when you need to interact with a list of web elements that share the same attributes, such as finding the number of rows in a table.
Use findElement if you expect only one element with the specified name attribute:
Note that if two or more elements exist matching the given locator, only the first element will be returned by this command.
WebElement usernameField = driver.findElement(By.name("username"));Code language: JavaScript (javascript)
Use findElements to find multiple elements matching the specified locator:
List<WebElement> listItems = driver.findElements(By.cssSelector("#myList li"));
int itemCount = listItems.size();
System.out.println("Number of list items: " + itemCount);Code language: PHP (php)
The findElements command may also be used to identify an empty list. In such a case, the command will return zero for the number of elements matching the given locator.
Interacting with web elements in Selenium
How to get the text value from an element
Open the Chrome browser and go to our website https://practice-automation.com/, which helps you practice web automation.
Right-click on the page and select Inspect.
Select the inspect icon on the top-left corner and then hover the mouse on the text that says Welcome to your software automation practice website!
It will show an HTML line related to that text.
Right-click on that line and select Copy > Copy XPath. We will use this XPath later in our Selenium test class.
Open IntelliJ and create a new project, package, and test class, similar to our previous example. You can also use the same pom.xml file.
Then, we will create our test class based on our URL and XPath.
package your_package_name;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class MyClass {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.get("https://practice-automation.com/");
WebElement headerTextElement = wait.until(d -> d.findElement(By.xpath("//*[@id='post-36']/div/h1/strong")));
String headerText = headerTextElement.getText();
System.out.println("Text from the element: " + headerText);
if (headerText.equals("Welcome to your software automation practice website!")) {
System.out.println("Text matches the expected value.");
} else {
System.out.println("Text does not match the expected value.");
}
} finally {
driver.quit();
}
}
}
Code language: JavaScript (javascript)
To run the test class, right-click on the class file and select Run ‘class_name.main()’ option.
Once we will start the run, it will navigate to the https://practice-automation.com/ and find the header element using the given XPath. Then, it will retrieve and print the text Welcome to your software automation practice website!. Lastly, it will compare the extracted text with the expected value and print whether the text matches or not.
How to select an option from dropdown
Go to: https://practice-automation.com/form-fields/
Find the dropdown named Do you like automation? and select Yes.
Right-click on the dropdown and select Inspect.
In the element tab, it has several attributes, such as name="automation", id="automation", and data-cy="automation". But for our Selenium test, we will use the id="automation" attribute.
Open IntelliJ, create a new project, package, and Java class. Use the same pom.xml file and the same import statements that we have used in our earlier example.
After the import statements, start writing the test class:
public class MyClass {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.get("https://practice-automation.com/form-fields/");
WebElement dropdownElement = wait.until(d -> d.findElement(By.id("automation")));
Select dropdown = new Select(dropdownElement);
dropdown.selectByVisibleText("Yes");
String selectedOption = dropdown.getFirstSelectedOption().getText();
System.out.println("Selected option: " + selectedOption);
} finally {
driver.quit();
}
}
}Code language: JavaScript (javascript)
To run the test class, right-click on the class file and select Run ‘class_name.main()’ option. After execution, the console window will display the selection of the Yes option.
Final thoughts on how to find an element in Selenium
In automation testing with Selenium WebDriver, learning various locator strategies is vital for effective automation scripts. Whether handling web applications or interacting with specific elements, knowing how to find elements using locators like ID, XPath, and CSS Selector can significantly improve your test efficiency. In such cases, with the proper use case in mind and a strong understanding of these locator techniques, you can improve the quality and performance of your test scripts. Using the right test attribute and following proven methods for locating elements ensures smoother execution. Happy testing!
Don’t miss these
Follow our blog
Be the first to know when we publish new content.
- How to find an element in Selenium - October 5, 2024
- Resolved: SessionNotCreatedException - October 2, 2024
- Katalon Recorder Automation Overview - September 12, 2024