In the modern digital high-speed world, it is necessary to deliver high-quality web applications. Automation tools such as Selenium have become indispensable for software QA today. It has become a powerful and versatile tool to automate browser actions on many teams. But in case you are new around here, you may be wondering what is Selenium and why everyone needs it.
Selenium is not a tool but a set of tools to automate browsers. Its open-source, cross-browser, and multi-language compatibility make it the most popular automation framework. However, while Selenium includes a wide range of features, there may be times when you need to change the defaults to suit your testing needs. An example of this is the creation of custom locator strategies.
In this article, we will discuss the importance, advantages, applications, and conceptual path for creating custom locator strategies through modifying the core of Selenium. This tutorial will help you appreciate the extent to which Selenium’s powerful architecture can be extended for your testing needs.
Why Default Locators Sometimes Fall Short?
Before looking into customizing locators, we must first understand what Selenium is offering us by default. Selenium has default locator strategies that allow us to select elements in an application, such as:
- ID
- Name
- Class Name
- Tag Name
- CSS Selector
- XPath
- Link Text
- Partial Link Text
For most applications, these locator strategies are sufficient. But as web applications grow at a rapidly increasing rate and adopt increasingly more complex features such as dynamic content, client-side rendering, custom UI frameworks, and shadow DOMs, the locators can sometimes become insufficient
The Drawbacks of Default Locators
- Dynamic IDs: Many elements have IDs that routinely change. Therefore, every time an automated script uses this ID, it breaks.
- Nested Components: React, Angular, and other modern frameworks are very nested and make simple selectors difficult.
- Non-semantic Markup: Many elements don’t have standard attributes. This leads to complicated XPath expressions to find the element.
- Shadow DOMs and Web Components: Sometimes standard locators don’t reach through or into Shadow DOMs and Web components.
When standard locators do not work properly, QA teams typically resort to patching the gaps, often using workarounds like brittle XPath expressions or complex chained selectors. This approach can slow the maintainability of your tests, create flaky tests, or require significant debugging effort. This is exactly where custom locator strategies are beneficial.
What are Custom Locator Strategies?
At its simplest, custom locator strategies allow testers to create new options to locate elements in the DOM. You may ask Selenium to find elements by the structure or the behavior of your app instead of using only built-in options.
Think of it this way: Selenium can find elements using some standard landmarks. Custom locator strategies provide entirely new landmarks for Selenium to use, which are designed uniquely for your work.
Use Cases for Custom Locator Strategies
Custom locators are a requirement with advanced or large-scale projects. There are plenty of common situations where a customized locator will add significant value:
Component-Based Architectures
Modern UI frameworks break pages into components that can be reused in several places. These components may have deeply nested structures with no unique identifiers. In this type of scenario, a custom locator will enable you to find elements by component name or by using data attributes or even using the logic of positioning.
Localization and Internationalization
In apps that support many languages, the displayed language tends to vary. This renders locators such as link text or partial link text unreliable. Custom locators give you the opportunity to specify locale-specific attributes or fallback consistent IDs.
Data Attributes
Many applications just implement their own custom data-* attributes to tag elements. If you commit to writing a custom locator to pull the data-test-id or data-role values, your test may be more stable and easier to read.
Accessibility Attributes
Many applications use accessibility attributes to make their applications accessible to individuals who may have some issues using regular interfaces. This includes the use of ARIA roles and labels, which can be used to create custom strategies to locate elements by using aria-label, role or aria-labelledby.
Business Logic
There are cases when selectors have to use business logic, not markup. To give an example, you may need to locate the second item on a list whose price is greater than 50 dollars. It is possible to address such domain-specific conditions with the help of a custom locator strategy.
Conceptual Understanding: How Selenium Interprets Locators
In case you intend to change or expand Selenium, you need to know how Selenium handles locators. An example would be when you enter something like By.id(“username”), Selenium accepts this as a command and gives it to WebDriver. WebDriver will then exchange messages with the browser and locate the element, and send it back to Selenium so that the next action can be initiated.
All of the locator strategies are handled by the By class, which simplifiesthe internal structure of the DOM. By introducing a personal strategy, you are introducing one more layer of this abstraction.
In order to understand this better, think about what is Selenium WebDriver. It is the component that bridges the gap between your test script and the browser. It accepts instructions, such as clicks or locators, and transforms them into actual browsing activity. Selenium without WebDriver has no way of interacting with the browser.
By changing this layer, you would inform Selenium about how to read your custom selector and find elements according to your own rules.
Benefits of Custom Locator Strategies
Why go through the effort of building something new when Selenium has so much to offer?
For a couple of reasons:
Enhanced Maintainability
Custom locators based on consistent attributes (data-test-id) or domain logic are able to better mitigate UI-based changes than brittle XPATHs or CSS selectors.
Enhanced Readability
Test scripts that use business terms (e.g., findElementByProductName(“Apple Watch”)) are easier for users to read and understand than obscure selectors.
Simplified Debugging
When locators are descriptive and abstracted, debugging tests that failed could be faster and easier.
Scale
Big teams can take advantage of a similar locator logic. Instead of every team member writing their own selectors, having custom strategies provides consistency.
With GenAI-native test execution platforms like LambdaTest, teams can run Selenium tests across a wide range of real browser and OS combinations. This ensures that custom locator strategies are not only reusable but also reliable in diverse environments. LambdaTest helps streamline cross-browser testing without adding infrastructure overhead. It’s a practical way to validate your locators under real-world conditions.
LambdaTest eliminates the need to install Selenium ChromeDriver or manage local browsers by offering a cloud-based Selenium Grid with built-in ChromeDriver support.
What You Get with LambdaTest:
- No setup required: ChromeDriver is pre-configured for all major Chrome versions.
- Run Selenium tests at scale: Use LambdaTest’s cloud infrastructure to run tests in parallel across multiple versions of Chrome, OSes, and devices.
- Cross-browser & cross-platform: Test on Chrome, Firefox, Edge, Safari, etc., on Windows, macOS, Android, and iOS.
- Real-time debugging and logs: Access console logs, network logs, video recordings, and screenshots.
- CI/CD ready: Seamless integration with Jenkins, GitHub Actions, CircleCI, and more.
Domain Specific Abstructions
You can include your product knowledge directly into the locator logic, allowing tests to better reflect business logic than technical architecture.
A Practical Path to Customization
Let’s outline a high-level conceptual path to implementing custom locator strategies through modifications to the Selenium core so that you quickly develop your own understanding.
Identify Duplicate Locator Logic
You should look for duplicated selector logic in tests. For example, if tests commonly search for elements with a data-test-id, it could be a good candidate for a custom strategy.
Define the Selector Language
You would decide how you want testers to express the new locator. Will you allow them to say By.dataTestId(“login-button”)? Or something more descriptive like By.componentName(“ShoppingCart”)?
Update the Core Locator Engine
You’ll want to extend the core internal Selenium classes that are responsible for resolving elements. This will usually mean extending the basic locator registry to include your locator strategy.
Define Resolution Logic
This is the code that tells Selenium how to interpret your new strategy and retrieve the appropriate elements from the DOM. Typically, you will be internally mapping your custom syntax to valid CSS or XPath code.
Add Fallbacks and Checking
What should happen if the custom locator did not find any elements? Keep in mind what you want to see in your error messages. Provide clear error messaging to assist with debugging.
Document and Train
Now it’s time to document your strategy and train your team on it. Well-documented strategies lead to adoption amongst the team, and well-documented strategies prevent confusion.
Best practices when customizing Selenium
Customizing Selenium’s core is a potent practice—but with great power comes great responsibility. To ensure that you are doing this properly, you should follow these best practices:
Avoid Overengineering
Only generate a custom strategy if there is an obvious benefit to doing so. Creating too many custom options tends to lead to confusion and misuse.
Isolate and Abstract
Make sure your custom logic is kept separate from your test logic. Only abstract the locator, so that if you need to change it, you only have to change the strategy and not every test.
Test the Locator Strategy Itself
Just like any other feature, write tests for your locator strategy, so you can check it works correctly with the variations of the DOM.
Versions and Control
If you’re working in a team, version-control your customizations in isolation and think about distributing custom locators as a library.
Don’t break compatibility
Custom strategies shouldn’t create compatibility issues with the base Selenium capabilities. Be sure to retain the option to fall back to a default locator when needed.
Wrapping Up: Embrace the Power of Customization
The true capability of Selenium is neither what it is capable of doing out of the box nor even the capabilities that it offers (especially in terms of locators). Progressive, more forward-thinking testing teams see the potential for customization, not only with how they test but also with how the test automation operates.
By using the customization of Selenium’s core to build custom locator strategies, you are ultimately not only writing test cases that are superior, but instead you are building the framework to reflect your application’s unique identity.
So next time you find yourself battling a flaky XPath or overly convoluted CSS selector, ask yourself, “Is it time to create a custom locator strategy?” More often than not, the answer will be yes.
