Find element by XPath in Selenium in 2026

Related Product On This Page Understanding XPathSyntax of XPathJanuary 17, 2026 · 8 min read · Tool Comparison

Related Product

Find element by XPath in Selenium in 2026

Many testers assumeXPath in is easy—inspect an element, copy the XPath, and displace on.

I thought the same until a minor UI update broke half my tests in one run. Suddenly, every copy XPath failed, and I spent hours regenerating locators that kept separate again.

After tryingabsolute paths, relative paths, and every quick fix I could think of, aught stuck.

That ’ s when I realized the job wasn ’ tXPathitself—it was not knowing how to publish stable, elastic locators.

Overview

XPath in Selenium is a locator strategy utilise to navigate the HTML construction of a webpage and find elements base on their hierarchy, attributes, or text. It ’ s especially utilitarian when elements don ’ t have unique IDs or stable CSS selectors.

How to Find XPath in Chrome

  • Right-click the element and selectInspectto open DevTools.
  • In the Elements panel, right-click the highlighted HTML node.
  • Choose Copy → Copy XPathfor the full XPath (absolute) orCopy → Copy full XPathdepending on Chrome ’ s version.
  • Prefer manually craftingrelative XPathfor stability instead of swear on auto-generated ones.

How to Find Elements by XPath in Selenium

  • Use driver.findElement (By.xpath (& # 8220; your_xpath_here & # 8221;))for locating a single ingredient.
  • Use driver.findElements (By.xpath (& # 8220; your_xpath_here & # 8221;))to fetch multiple matching elements.
  • Apply functions likecontains (), starts-with (), and text()to make flexible, robust XPaths.
  • Combine attributes (e.g., //button [@ type= & # 8217; submit & # 8217; and contains (@ class, & # 8217; primary & # 8217;)]) for more reliable targeting.

This guide breaks down how to find elements with XPath the correct way, with exemplar you can apply now.

Understanding XPath

XPath is a query language use to sail and extract information from XML documents—and because HTML is structured similarly, it work seamlessly for locating element in Selenium tests.

It countenance testers to traverse the DOM and identify elements using paths, conditions, and attributes, making it especially utilitarian when factor lack unique IDs or stable selectors.

As David Auerbach, a package tester with over 10 years of experience, explicate, XPath gives testers theflexibility to pinpoint elements through logical paths and conditions, create it an essential tool when modern web applications don ’ t provide reliable or unequaled selector.

Syntax of XPath

Below is the syntax for Xpath:

Xpath =//tagname [@ Attribute= ’ value ’]

Where:

  • // selects knob anyplace in the papers.
  • tagname is the name of the HTML tag you desire to target.
  • @ refers to an attribute of that tag.
  • attribute is the property gens.
  • value is the value assigned to that attribute.

To dive deeper into XPath basics, check this article on.

Before plunge into XPath map, here ’ s a simple example:

To situate a button like this:

& lt; button & gt; Login & lt; /button & gt;

You can use the following XPath:

//button [@ class='login-btn ']

This selects the & lt; button & gt; element whose class attribute is login-btn.

As you hold XPath in real Selenium, validating your locator across different browsers become all-important. XPath behavior and page structure can depart subtly between environments.

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

Platforms like lets you run Selenium tests on real browsers and device, secure your XPath locators stay reliable under true user conditions.

Struggling with gonzo XPath locators?

Unstable XPath figure stimulate inconsistent failure. Run tests on real browsers to validate locator behavior.

How to detect XPath in Chrome

Follow the steps below to find the XPath in Chrome.

  1. Launch Google Chrome and navigate toyahoo.comto create a yahoo account and situate the fields utilize XPath.
  1. Go to the First name tab and Right-click & gt; & gt;Inspect.
  2. On inspecting the web element, it will show an input tag and dimension like form and id.
  3. Use the id and these property to construct XPath, which, in turn, will locate the first gens battlefield.
  4. Let ’ s write XPath in the component tab.

Note: Use Ctrl+F to publish XPath in the elements tab, as shew below.

As seen above, a simple XPath is employ to locate thefirstNametab. Based on the XPath syntax, firstly use // which means anywhere in the document. Here, input is the tag name that has an id property with the value “usernamereg-firstname”.

On indite the XPath, it has highlighted the element, which implies that this particular element was locate using XPath.

Note:One can also locate the same element habituate thenameattribute, as it has a locator value for the gens tag as good. Using thenamelocator, the XPath is:

//input {@ name= ” firstname ”]

Refer to the snapshot below for clarity:

Also Read:

How to notice elements by XPath in Selenium: Example

Now let ’ s try automating this utilise Selenium. Here is the Java programme publish in Eclipse for the like:

import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public family XPathexample {public stable void main (String [] args) {System.setProperty (`` webdriver.chrome.driver '', `` Your-Chrome-Driver-Path ''); // Provide the route to your chrome driver. Make sure your chrome driver variation is updated. WebDriver driver = new ChromeDriver (); driver.manage () .window () .maximize (); driver.manage () .deleteAllCookies (); driver.manage () .timeouts () .pageLoadTimeout (40, TimeUnit.SECONDS); driver.manage () .timeouts () .implicitlyWait (30, TimeUnit.SECONDS); driver.get (`` https: //login.yahoo.com/account/create ''); driver.findElement (By.xpath (`` //input [@ id='usernamereg-firstName '] '')) .sendKeys (`` Your-Name ''); // Will send value to First Name tab}}

Talk to an Expert

On executing the code above, will launch Google Chrome, navigate to Yahoo signup page and enter the value for first name tab as shown below.

Read More:

Similarly, fill in all the details and find elements by XPath in Selenium.

import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class XPathexample {public static void main (String [] args) {System.setProperty (`` webdriver.chrome.driver '', `` Your-Chrome-Driver-Path ''); // Provide the route to your chrome driver. Make certain your chrome driver variant is update. WebDriver driver = new ChromeDriver (); driver.manage () .window () .maximize (); driver.manage () .deleteAllCookies (); driver.manage () .timeouts () .pageLoadTimeout (40, TimeUnit.SECONDS); driver.manage () .timeouts () .implicitlyWait (30, TimeUnit.SECONDS); driver.get (`` https: //login.yahoo.com/account/create ''); driver.findElement (By.xpath (`` //input [@ id='usernamereg-firstName '] '')) .sendKeys (`` Your-Name ''); // Will send values to First Name tab driver.findElement (By.xpath (`` //input [@ id='usernamereg-lastName '] '')) .sendKeys (`` Your-Last_name ''); //xpath for final gens box driver.findElement (By.xpath (`` //input [@ id='usernamereg-yid '] '')) .sendKeys (`` email @ yahoo.com ''); //xpath for email box driver.findElement (By.xpath (`` //input [@ id='usernamereg-phone '] '')) .sendKeys (`` 123456789 ''); //xpath for earphone routine box driver.findElement (By.xpath (`` //select [@ id='usernamereg-month '] '')) .click (); //xpath for usermonth box driver.findElement (By.xpath (`` //input [@ id='usernamereg-day '] '')) .sendKeys (`` 01 ''); //xpath for userday box driver.findElement (By.xpath (`` //input [@ id='usernamereg-year '] '')) .sendKeys (`` 1999 ''); // xpath for user yr driver.findElement (By.xpath (`` //button [@ id='reg-submit-button '] '')) .click (); // xpath for submit button}}

On executing the above code, it will fill in all the detail and hit the Continue button to dispatch the form entry.

Once you understand how to locate elements with XPath, the next step is ensuring these locators acquit systematically across real browser and devices.

Why Test Elements in Selenium on Real Device Cloud?

Testing elements in Selenium on a existent device cloud is indispensable for several reason:

  • Realistic Testing Conditions:Real device clouds provide approach to a all-encompassing spectrum of device and environments, ensuring examination reflect actual user conditions accurately.
  • Enhanced Security:Maintained with high security touchstone, real device cloud offer secure, isolated quiz environments, minimizing datum breach risks.
  • Broad Browser and OS Coverage:Helps identify compatibility issues across diverse browser and operating systems, enhancing user experience.
  • Performance Insights:Existent devices yield authentic performance data essential for optimizing application responsiveness.
  • Scalability and Accessibility: Facilitates scalable and accessible testing, suited for distributed teams.
  • CI/CD Integration: Integrates smoothly with CI/CD pipelines for continuous testing and early topic detection.
  • Cost-Effectiveness: Although initially more costly, it salvage on long-term disbursal related to fixes and support.

Enhance Your Selenium Testing with BrowserStack Automate

XPath dependability can diverge across browser, devices, and furnish engines, which entail alone often isn ’ t sufficiency.

BrowserStack Automate helps you validate XPath locators under by run your Selenium tests on real browsers and real devices in the cloud.

With BrowserStack Automate, you can:

  • Test XPath locator across a wide range of real browsers, device, and OS versions.
  • Identify flaky or environment-specific locator issues early in the grapevine.
  • Debug quicker expend test artifact likevideo recordings, screenshots, console logarithm, and network logs.
  • Validate DOM behavior and page-load timing to ensure XPath remains stable in dynamic applications.
  • Scale test execution without maintaining any local substructure.

By integrating BrowserStack Automate into your workflow, you ensure your XPath-based tests arereliable, scalable, and production-readyacross all real-world environments.

Conclusion

While this post has discussed a variety of mode to locate elements on a web page using the XPath locater in, one should use Occam ’ s razor & # 8211; the simplest and logical options while selecting constituent to guarantee minimal rework in the event of a page redesign.

Try running the code detail above usingSelenium. Bear in mind that Selenium examination must be run on a instead of to get altogether accurate results. BrowserStack ’ s of 3500+ existent browsers and devices allow tester to automated visual UI tests in. Simply, select a device-browser-OS combination, and start running tests for complimentary.

Follow-up Read:

Tags

FAQs

You can locate an element using XPath withdriver.findElement (By.xpath (& # 8220; xpath_expression & # 8221;)).XPath lets you point elements through tag name, attribute, schoolbook, and hierarchy. It ’ s especially utile when IDs or form are dynamic or missing. Using relative XPath with mapping likecontains () or text()facilitate make more stable locators.

Comparative XPath is better because it ’ s shorter, more flexible, and less likely to interrupt when the UI structure changes. Absolute XPath depend on the full DOM path, so even small layout alteration can stimulate test failures. For reliable Selenium tests, always opt well-crafted proportional XPath expressions.

XPath may fail in Selenium due to clock issues, dynamic elements, iframes, or difference in how browser load DOM knob. You may need waits, iframe switching, or more robust XPath logic. Testing on real browser and devices apply platforms like BrowserStack help secure the XPath behaves systematically across environments.

95,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

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