Locators in Selenium: Types and Examples

January 15, 2026 · 10 min read · Tool Comparison

Blog / Insights /
Locators in Selenium: Types and Examples

Locators in Selenium: Types and Examples

QA Consultant Updated on

Learn with AI

Linkedin

Facebook

X (Twitter)

Mail

Learn with AI

Every action you automate in Selenium start with one thing: encounter the right web constituent. That ’ s where locators come in. They guide Selenium to the exact button, input field, or text box it needs to interact with.

Locators in Seleniumare essential. Without them, you ca n't click a button, fill out a form, or control if a substance appears on the screen. They 're the foundation of every examination case you write.

In this article, we ’ ll walk you through:

  • What are locators in Selenium?
  • What are Selenium locators habituate for?
  • How relative locators act in real projects
  • Types of locators in Selenium and when to use each
  • Best practices and troubleshooting tips

Let ’ s get started!

What are Locators in Selenium?

Locators in Seleniumare methods used to find and interact with web component during automated testing. They help you target specific component of a web page so that Selenium can perform actions like clicking, typing, or checking values.

Every web page is made up of elements. These include comment fields, buttons, nexus, ikon, and more. When you automatise a login operation, you need to locate the email field, the parole box, and the submit push. That ’ s where locators come in.

You might use a locator to find the “ Search ” box on a product page. Or to identify the “ Add to Cart ” button next to a product ikon. You can even use locators to control if a success message appear after a pattern is submitted.

Precision thing. When your locator identifies the right element, the tryout runs smoothly. But when it points to the improper one, the script click the wrong spot or enters data in the improper battleground. That ’ s why writing accurate locators is a nucleus skill in Selenium mechanization.

Locators in Seleniumafford your tests the power to behave like a existent user. They let you control what to essay and how to interact with the interface in a stable, reliable way.

What are Selenium locators used for?

Selenium locatorsare used to tell your test playscript just where to look and what to interact with on a web page. They make it possible for Selenium to behave like a user who knows where to click, character, or read.

When you want to tick a button, you use a locater to find it. If you want to enter text into a form battleground, the locator narrate Selenium which field to use. You can also use locater to educe product names, prices, or content from the page after an action is completed.

Examples of locater in Selenium

Let ’ s take a uncomplicated checkout flow. First, your examination uses a locator to click “ Add to Cart. ” Then it apply another locator to open the cart. The check push, the delivery speech field, and the payment form: all require locators. Without them, Selenium can ’ t complete the flow.

Locators in Seleniumenable you to automate real-world action from start to finish. They ensure your tests are exact, repeatable, and meaningful. That ’ s what makes them so important to every test you indite.

Common Use Cases of Relative Locators in Real Projects

Relative locatorsare especially useful when traditional locators like ID or Class are miss or inconsistent. They let you find elements based on their position relation to others. This works well in real-world labor where layout subject just as much as attributes.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Here are a few practical model where comparative locators help you build voguish tests:

  • Login pages:You can find the password field by locating it just below the username field. This is helpful when the password remark has no unequaled property.
  • Product listings:You can target the toll label that seem directly under a product title. Or place the “ Add to Cart ” button placed just beneath the product icon.
  • Form proof:When a user enters invalid remark, an error substance ofttimes look beside the field. Comparative locator help you regain these messages based on their position next to the stimulus.
  • Dashboards:Many dashboards exhibit widgets or indicators near headings. You can situate a chart that sits beside a rubric or a status badge placed next to a user gens.

These example establish howrelative locators in Seleniummake your test cases more readable. Instead of relying on deep XPath queries, you draw elements by their relationships. That ’ s the way humans see a page.

This approach gives you flexibility. It reduce the need for hard-coded selectors and makes your tests more adaptable to UI changes. That ’ s why relative locater are a strong gain to your Selenium toolkit.

📚Read more:Relative Locators in Selenium: Types and Examples

Proportional Locators vs Traditional Locators

Traditional locatorslike ID, CSS Selector, and XPath have been used in Selenium since the beginning. They are tight, direct, and wide supported across frameworks. More recently,relative locators in Seleniumbe insert to solve layout-based targeting challenge. They bring new tractability to test mechanization.

Here ’ s a comparison to facilitate you decide when to use each type:

Aspect Traditional Locators Relative Locators
Stability Highly stable when utilise unique IDs or name Helpful when IDs are missing or change frequently
Readability XPath and CSS can be long and detailed Easy to say and describe using element position
Maintainability Needs updates if UI structure or assign change Can reduce effort in dynamic or visual layout
Flexibility Great for targeting complex or nested elements Best for visual or spatial relationship between factor

This comparison present that both locator types function a determination.Relative locators in Seleniumdon ’ t replace traditional locator. They work alongside them to make your trial more adaptable and expressive.

The best strategy is to match the locator eccentric to the construction of the page. Use what fits the use case, and you get better test reporting with less effort.

Which is the most Effectual Locator for Selenium?

The most efficient locator in Seleniumdepends on your application and the way elements are structured. There is no single best choice for every position. The right one is the locator that offers speed, constancy, and long-term maintainability in your tryout rooms.

  • ID is much the first choice when it is usable. It is unique, fast, and easygoing to say. If your UI assigns coherent IDs to factor, this locator is a outstanding fit for high-performance test scripts.
  • When IDs are miss, CSS picker act good for styling-based target. They handle layered factor and attribute-based filter swimmingly.
  • XPath offers even more power. You can use it to move across different parts of the DOM and combine multiple conditions.

Which Selenium Locators to use when?

Locators in Selenium provide multiple slipway to identify component, but each has its own ideal use cause. Selecting the right one bet on the attributes available on the page, how stable those attribute are, and how complex the DOM structure is. The better your locator choice, the more reliable and maintainable your test scripts get.

  1. By.id()– Your initiatory choice for stable elements
    If an element has a unique, static ID attribute, always start with By.id (). It ’ s the fast and about unmediated locator because browser can adjudicate IDs natively without supernumerary computation. This keeps your tests simple and zip up execution.
  2. By.name () or By.className ()– When IDs aren ’ t stalls
    If the ID dimension is missing, duplicated, or dynamically generated, try By.name () if the element ’ s name dimension is unique, particularly for kind battleground. If the name attribute is also unreliable, By.className () can work, but be careful with classes that are shared across multiple component.
  3. By.cssSelector () or By.xpath ()– For complex or nested structures
    When the element is buried in a complex DOM or when you need to chain multiple attributes, By.cssSelector () is often cleaner and quicker than XPath for most modernistic browser. Use By.xpath () only when you need very specific structural relationship (such as traversing up the DOM) or when the page lack sufficient IDs, names, or classes to make a true CSS selector.
  4. By.linkText () or By.partialLinkText ()– For hyperlinks
    If you ’ re direct nexus, By.linkText () check the full seeable text exactly, making it clear and easy to read. When solitary piece of the link text is stable or consistent, By.partialLinkText () allow you correspond simply a fragment, which is useful for dynamic text changes.
  5. Relative locators like above (), below (), or near ()– For layout-based targeting
    Selenium 4 introduced relative locator to let you find component based on their position congenator to others. Use these when the page lack reliable property but the layout is predictable. For example, you can place a label and then situate an input direct below it without relying on brittle selectors.

Always prefer the locator that is simple and reliable. A short, stable locator is easier to keep and easygoing to read. That helps your squad motility quicker without guessing which element is being screen.

Selenium locatorsare flexible. When you jibe the correct case to the right task, your automation becomes suave and your tests stay solid through UI changes.

Best Practices for using Locators in Selenium

Writing strong locators is one of the easiest ways to meliorate test stability. These best practices help you establish mechanization that lasts longer and work more smoothly across UI changes.

  • Use unique IDs whenever possible.
    IDs are fast, stable, and easy to read. If an element has a unique ID, use it to keep your locator little and efficient.
  • Choose locater types that match the structure.
    Use CSS selectors for simple layouts. Use XPath for complex paths. Use relative locators when elements are placed near each other.
  • Use descriptive name in your locater repository.
    A clear name like loginButton or emailInputField makes it easy for any squad member to understand and recycle.
  • Favor CSS selectors over XPath when execution matters.
    CSS selectors are generally faster. They also work well in most browser and are easier to write for mutual patterns.
  • Keep locators centralized and reusable.
    Store all locators in one spot. This make maintenance easier when the UI updates and aid squad work in sync.
  • Review and update locators regularly.
    As your app evolves, your locator strategies should evolve too. Refreshing them keeps your tests accurate and aligned with the product.

Following these practices aid reduce rework and amend the caliber of yourlocators in Selenium. It too speeds up collaboration, specially when your squad scales or your application grows more complex.

Troubleshooting Relative Locators

Proportional locator in Seleniumare helpful when element are positioned near each other on the screen. They work well in many real-world scenarios. Still, like any locator strategy, they benefit from careful validation and serious-minded use.

  • Wrong factor be selected
    When multiple elements meet the same precondition, Selenium might pluck the first lucifer. This can hap when two field are placed below the same label. To improve accuracy, down the quotation element or combine more than one stipulation in your locater.
  • Overlapping ingredient
    Some layouts place icon, tooltips, or streamer on top of early elements. Selenium may interact with the top layer. Before tick or typecast, check that the right element is visible and not covered. You can also confirm its layer utilise styles or customs attributes.
  • Dynamic layouts
    Responsive pages adapt based on screen sizing. This modify the view of elements. Relative locators work best when the layout stays consistent. Use waits, formalise the DOM, and duo relative locators with other attributes when the layout is liquid.
  • Ambiguity in “ near () ”
    The nigh () method target elements that are visually near. When several component sit near the reference, the result may be unclear. Use “ near ” with caveat and combine it with another locator type to confirm the exact target.

Every locator postulate a agile proof step. When you confirm that yourrelative locatorselects the right element, your test becomes more stable. This pocket-size use facilitate you avoid issues before they affect the whole examination flow.

Explain

|

FAQs

What are locater in Selenium?

+

They ’ re methods expend to find and interact with web elements so Selenium can click, eccentric, or verify content during automated tests.

What are Selenium locators used for in real examination flows?

+

To target elements like fields, buttons, nexus, messages, and complete end-to-end flows such as login, add-to-cart, and checkout.

What is the virtually efficient locater in Selenium?

+

It depends on the page, but By.id () is often better when IDs are alone and static because it ’ s tight, unmediated, and easy to preserve.

When should you use CSS selectors, XPath, or link text locater?

+

Use CSS selectors for many common patterns (often cleaner/faster), XPath for complex structural relationship, and By.linkText () / By.partialLinkText () for hyperlinks.

What are Selenium relative locator, and when are they useful?

+

Comparative locator (like above (), below (), near ()) find elements by position relative to others—useful when IDs/classes are missing but the layout is predictable (e.g., error message beside an input, password field below username).

Vincent N.
QA Consultant
Vincent Nguyen is a QA adviser with in-depth sphere noesis in QA, package testing, and DevOps. He has 5+ years of experience in crafting substance that resonate with techies at all levels. His interests span from indite, engineering, to building cool clobber.

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free