Selenium WebDriver interacts with web elements on a webpage by locating them and then performing actions like clicking, selecting, or entering text. The Selenium WebDriver interface offers two methods, findElement() and findElements(), to identify elements on the page.
The findElement() method is used to locate a single, unique web element, while findElements() is used to locate a list of web elements on the page.
What is findElement by ID in Selenium
findElement() method of Selenium WebDriver’s interface takes in the By object as a parameter and returns a web element object. By object can be used with different locator strategies such as ID, name class name, link text, etc.
This web element later can be used to perform actions like clicking, entering text, hovering on it, etc. You can use the findElement() along with the By.Id locator to locate an element using its id.
Locators in Selenium
Locators in Selenium WebDriver are crucial for identifying elements on a web page.
Locators in Selenium
- ID
- Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- XPath
- CSS Selectors
Each locator type has its own syntax and is suited for different scenarios based on the structure of the HTML and the attributes of the elements.
1. ID: Locates an element using its unique ID attribute. This is one of the fastest and most reliable locator types.
2. Name: Finds elements by their name attribute. This can be useful when multiple elements share the same name.
3. Class Name: Targets elements based on their class attribute. This is useful for selecting multiple elements that share a class.
4. Tag Name: Locates elements by their tag name (like, input, button, div). This can be used to find all elements of a specific type.
5. Link Text: Specifically used to locate anchor (<a>) elements by their visible text. This is helpful for finding links.
6. Partial Link Text: Similar to Link Text, but allows for partial matching of the anchor text, making it useful for long or dynamic link text.
7. XPath: A powerful and flexible locator that uses XML path language to navigate through elements and attributes in the DOM.
8. CSS Selector: Utilizes CSS selectors to find elements. This is often faster than XPath and can be very expressive for complex selections.
Read More: Quick XPath Locators Cheat Sheet
Why ID is a preferred locator for finding elements
ID is preferred over any other locator due to following reasons:
1. Unique: An id associated with the element on the web page is typically unique which ensures that it locates a single element only. This reduces the risk of identifying multiple elements and makes it less error prone unlike other locators such as class name which may locate multiple elements.
2. Simple and easy to read: Id names are generally concise and straightforward making them simple to use in test scripts and easy to maintain.
3. Speed and efficiency: Selenium WebDriver can quickly locate the element by using its ID. It is a much faster approach than using any other locator like class name or XPath which may involve more complex structure. This makes ID the fastest and most efficient locator among all the other locators of Selenium WebDriver.
4. Stable and reliable: IDs are very rare to change unlike other locators like CSS selectors and class name which may be dynamically generated or may change as the page updates. This makes the ID as the most stable and reliable locator as compared to the other locators.
Syntax for Finding Elements by ID
WebElement elementName = driver.findElement(By.id("LocatorValue"));
- WebElement is the Selenium interface that represents the HTML element on the web page which allows users to interact with the element.
- driver is the WebDriver instance that controls the browser.
- findElement is a method that is used to locate a single element on the web page. If there are multiple elements matching the criteria, it will return the first matching element. If no element is found Selenium will throw NoSuchElementException.
- By is a class in Selenium used to locate elements in different ways.
- By.id(“LocatorValue”) is the unique ID of the web element which you need to locate.
- The element variable is a reference to the WebElement found by the findElement() method.
How to Find Element by ID in Selenium
Follow the steps below to find an element by its ID using the By.id() method
Prerequisites
1. Install Java Development Kit (JDK):
- Before installing Selenium, make sure to download Java from the Oracle Download page.
- Set the JAVA_HOME path variable in System’s environment variables.
- Verify Java is installed correctly by opening the command prompt and running the command as “java -version”.
2. Set Up the IDE: Set up and use Eclipse or IntelliJ as the editor for writing Java code.
3. Selenium WebDriver: Add Selenium Jars in the project or add Selenium Java dependencies if you are using a Maven project
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.27.0</version> <!-- Choose the latest version --> </dependency>
Code example
public class GetElementById { WebDriver driver; @Test public void clickGetStartedFree() throws IOException { driver = new ChromeDriver(); driver.get("https://www.browserstack.com"); try { WebElement getStartedFree= driver.findElement(By.id("signupModalProductButton")); getStartedFree.click(); Assert.assertTrue(driver.getCurrentUrl().contains("sign_up")); }catch (Exception e) { System.out.println("Assert failed: "+e.getStackTrace()); } driver.quit(); } }
Code explanation:
1. The findElement(By.id(“signupModalProductButton”)) locates the Get Started element with the id “signupModalProductButton”.
2. After the element is located, the button is clicked.
3. Finally, an assert is performed to verify the page URL.
When to use Finding Element by ID in Selenium
Finding an element by id is a highly efficient and most used method for locating web elements. Following are some scenarios when you should use By.id() to locate elements.
- When any element has a valid and unique ID, it is best to locate the element by id. Finding an element by id is the simplest and easiest method among all the other locator strategies. The complexity of the test code is reduced which is greater while creating locators via XPath and CSS selectors.
- Static and stable IDs: If the ID of the web element is static and does not change even after the page reloads, it is the most suitable method to locate the element. Even when the page reloads and the structure is changed, you do not have to worry about breaking of the locator as the ID value will mostly be consistent and unaltered.
- Well-defined web pages: If you are working with a website that adheres to best practices in terms of design and structure, most elements have well-defined and unique IDs. Working with such well-structured websites makes it ideal to locate the elements by their ID value.
- Need Faster execution: Locating the web element by its ID is the fastest and most efficient method as IDs are unique. Typically, browsers use internal indexing for IDs which allow them to quickly locate the element in the DOM without the need of scanning the entire HTML document.
Best Practices when Finding Element by ID in Selenium
Follow below best practices when finding element by id to ensure that the tests are reliable, maintainable, and efficient
1. Use unique IDs: Ensure that the id attribute for the element to be located should be unique and descriptive across the page. Non-unique or duplicate id for any element may lead to inconsistent behaviour and flaky tests execution.
2. Avoid using dynamic IDs: Generally, ID is unique for the elements on the web page, however for some web pages, the ID value may change on page reload or DOM refresh. For such scenarios, the ID is not the valid and reliable locator to use and you should combine it with other locators like XPath or CSS selectors to make the locator more robust.
3. Avoid repetitive findElement() calls: If there is a need to interact with the same element multiple times, instead of calling findElement() every time, store the web element reference and reuse it. Repeated DOM lookups are inefficient and slow down the test execution.
4. Use explicit waits: Implicit waits are the global waits which may lead to unpredictable results and therefore, explicit waits should be used which allows you to wait for the specific conditions before proceeding for any action to avoid any exception.
If Selenium tries to interact with an element that is not completely loaded, it may throw an ElementNotInteractableException. Therefore, to avoid such exceptions it is always a good practice to use explicit waits wherever possible.
5. Use combination of IDs with other attributes: Sometimes, ID alone can be insufficient to locate unique elements on the web page. When the id is ambiguous, consider combining ID with other locators such as class name, name, or CSS selectors to create more robust and stable locators.
6. Test on multiple browsers: Locating elements by ID is the most reliable and efficient way. However, it is advisable to test your Selenium scripts on multiple browsers like Chrome, Firefox, Safari, etc. to ensure that it functions consistently across all browsers without any discrepancies or differences.
Use real device cloud platforms like BrowserStack Automate to test on real browsers and devices. BrowserStack Automate provides access to 3500+ real devices and browsers to test under real user conditions.
BrowserStack Cloud Selenium Grid allows you to run Selenium tests on multiple devices and browser combinations parallelly to save time, while maximizing coverage.
Conclusion
FindElement by ID is the simplest and fastest way to locate web elements on the web page. You would have a solid foundation for automating web applications by mastering how to find elements by ID in Selenium.
Selenium is the #1 choice among the web automation testers for creating robust and stable automation scripts and likewise BrowserStack is the #1 Cloud platform which testers could use to run their tests on 3500+ devices, browsers and platforms!
If you are eager to start your web automation journey, try exploring BrowserStack Automate to help you in your automation journey by signing in today!