Mastering Dynamic XPath in Selenium
On This Page What is XPath and Why is it Important in Selenium?April 19, 2026 · 15 min read · Tool Comparison
has a significant role in cut the testing efforts and improving the lineament of the web application by testing it in various device and browsers. is one of the which testers can use to automatize web applications. identifies the web elements on the web pages with the help of and XPath is one of the most pliant ways to regain. XPath is an acronym for XML Path language which is a query-based words utilize to sail and select node in an XML document using path-like syntax. When general locators such as ID, name, class are unable to find the element, XPath can be used to locate them. is employ to traverse and interact with the HTML construction of a web page. XPath plays a vital role in locating the web elements in the web page that can be later interacted such as click, mouse-keyboard actions, sendKeys, etc. Where, // denotes the current node, tagname is the tagname of the craved node, @ is habituate to select the appropriate attribute, attribute is the name of the property and value is the attribute value. In the above example, to locate “Complimentary Trial” button the XPath would be, Read More: Below are some of the main reasons why XPath is pivotal in Selenium: 1. Cross-browser fit: XPath locater works across various browsers without any exception in finding elements. This makes it the most reliable, effective and robust way to locate and interact with the component on the web page. 2. Supports complex queries: You can make XPath locators by combining different complex criteria of elements such as id, grade and text use. XPath can too be used to place elements via hierarchic relationship such as parent-child, ascendent and sibling elements. 3. Creates absolute and relative path: XPath helps locating web elements use absolute and relative paths where absolute XPath determine the full itinerary which begin from the root node and relative XPath use a more svelte approach in selecting the web elements. Absolute way: Relative path: 4. Locates elements dynamically: Some factor are dynamic in nature and can not be easily located with an factor & # 8217; s single dimension. XPath can be utilise to create dynamical locators for such elements with the help of logical operations such as ‘ AND ’ and ‘ OR ’ and contains functions. Example: Dynamic XPath is a method of finding web elements on a webpage when their attributes alter dynamically. It can be used to place elements with dynamic attribute values and is more flexible as compared to motionless XPath which depends upon doctor property such as id and name. Dynamic XPaths are especially good for automating dynamical web applications where elements may vary over clip or where their dimension continuously change with each page freight. XPath is broadly classified into two types: dynamic and static XPath. Though both the way are used to locate the web elements, they vary in how they handle changes in the web page ’ s structure and attributes. A tabular difference between the two would provide more insight, making it easier to distinguish between them. Most modern web applications consist of dynamic web pages which change very frequently. Dynamic XPath can be employ for such complex and ever-changing web pages, which volunteer flexibility, adaptability, and robustness in locating the web elements. Below are some of the significant reward of using dynamic XPaths in web automation. 1. Flexible and adaptable: Dynamic XPath is really pliable in terms of creating robust locater as it does not contain the full path of the ingredient starting from the node of the DOM and rather it uses the exact tag name of the element along with the attribute (s). You can also use relationship, fond text matchers with contains map to create them. Example: here if the aria label value alteration from “ logo_123 ” to “ logo_345 ”, still this locator will act. 2. Creates racy and accurate locators: Some elements on mod web application are dynamic which continue updating their attribute value on page load or refresh. Locating such elements via general locators such as name, ID and category would not be executable as these property may change when the DOM construction changes. Using dynamic XPath, you can create robust and accurate locator which consist of property ’ s partial value. So still if the dimension value changes for a page load, it will locate the element with the partial attribute value. 3. Easy to maintain and scale: As dynamic XPath reflection are flexible and adaptable; it is very easy to maintain yet when the web page gets updated or changed in any circumstances. Dynamic XPaths are highly stable and unlikely to change, get them ideal for scaling mechanisation exam across different browsers and support cross-browser examination. 4. Less likeliness of test breakage: Dynamic XPath leverages weather such ascontains (), starts-with (), ends-with (), text(), which makes the locater stable and resilient that are less likely to break when the page is review or the elements are reorder. 5. Supports complex conditions: Dynamic XPath verbalism support more complex and advanced query features such as parent-child/ sibling relationship, contains and text map, logical operator, etc. Selenium relies on locator strategies to find and interact with elements on a web page. Out of the 8 locater strategies, ID, class, and name are the most effective for uniquely identifying ingredient. However, when an factor is dynamic and its attribute value changes oft, XPath is the best choice for tester. To write XPath locators in Selenium, you have to use XPath expressions in the By.xpath () method to locate elements. Here are the common ways to pen XPath expressions: 1. Locating by Tag Name: XPath can be used to select elements by their tag name. Example: This will get a list of button element present in the DOM 2. Locating by Attribute: XPath can be used to select elements based on an attribute & # 8217; s value. Example: This will locate a button with attribute value as ‘ submit ’ 3. Locating by Text Content: XPath can be used to select elements by matching the precise textbook they contain Example: This will place a button which has text as ‘ Register ’ 4. Using contains () for Partial Matching: XPath can be employ to take elements based on the partial dimension value. Example: 5. Using starts-with () and ends-with (): When the start of the attribute value is known and end is dynamic or when the end portion of the attribute value is known and part is dynamic, starts-with and ends-with function can be used. Example: Note:starts-with and ends-with purpose are useable in 2.0 and not in XPath 1.0 Read More: To use XPath in Selenium, you need to use thefindElement ()method to locate the element, followed by an action such asclick(), sendKeys (), or any other Selenium interaction. Here is an example in Java using Selenium WebDriver: Locating an element by XPath and clicking it: For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users. You can create dynamic XPath in Selenium utilize different methods. Each of them has their own utility which is discussed below with example. Ways to create Dynamic XPath in Selenium: 1. Using individual slash (/) XPath create with individual slash is known as out-and-out XPath. Absolute XPath for “Free Trial” button in BrowserStack domicile page is, 2. Using double slash (//) A double diagonal is used to create a relative XPath. Example: 3. Utilizing individual attribute If you want to create a XPath with just one property along with the tagname or no tagname, it can be written in follow ways, Example: 4. Utilizing multiple property If you need to make a XPath with multiple property along with the tagname or no tagname, it can be written in following slipway, Example: 5. Using Logical manipulator Logical operators such as ‘ AND ’ and ‘ OR ’ can also be used to make dynamic XPaths. Example: 6. Using contains () The contains () function in XPath is used to jibe an element ’ s attribute value or text message that contains a specific substring. This is helpful when the entire attribute is active but a piece of it remains constant. Example: hither it will match any button ingredient whose id contains “ submit_ ” and even if the id value changes to ‘ submit_123 ’ or ‘ submit_456 ’, it will still jibe it. 7. Using text (): The text () map matches the element based on its visible text content. Example: 8. Using starts-with (): The starts-with () function matches an element whose attribute value depart with a specific string. This is useful when the initial portion of the attribute value remains never-ending but the continue part is dynamic. Example: 9. Using ends-with ():The ends-with () function match an constituent whose attribute value ends with a specific string. This is useful when the trailing component of the attribute value remains constant but the initial portion is dynamic. Example: 10. Using contains () with schoolbook (): You can combine contains () and text () functions to match an element that check a specific text. Example: 11. Using parent and child relationships: You can use parent-child relationship to sail between elements in the DOM to locate parent or child elements that are relative to each early. Example: 12. Using ancestor, descendant, following and preceding axes: XPath permit you to locate an element in relation to another constituent that has a logical relationship with it. Consider the below HTML code snippet to translate ancestor and descendent relationship. To select all ancestors of the img tag, XPath would be, To select img tag inside the div with id= ’ header-habitat ’, XPath would be, Consider the below HTML code snippet to understand the following and preceding relationship. To choose the button that comes after div with id= ’ lang1 ’, XPath would be, To take the button that get before div with id= ’ lang2 ’, XPath would be, Findling web constituent with dynamic XPath in Selenium is an important skill when automatise web applications which experience dynamic elements. It helps in locating the elements with elastic strategies such as partial lucifer, relative positions, and using logical operators. With the supporter of the Java codification example below (in Step 9), run in BrowserStack ’ s Automate product, you will gain a detailed penetration into how to locate component utilise Selenium WebDriver. To run the test playscript on using BrowserStack SDK, follow the step refer below: Step 1. Download from the GitHub page. Step 2. Once it is downloaded, unzip it in a desired positioning in your local scheme. Step 3. Import the project inEclipse via File- & gt; Import - & gt; General - & gt; Projectsfrom Folder or Archive in Eclipse. Step 4. Once the labor is imported it should experience a structure like below. Open browser.yml file which contains all the required capabilities to run the trial on BrowserStack platform. Step 5. Set username and parole in thebrowserstack.ymlfile available at the root directory. Step 6. You can run the testcases on multiple devices and browser combination uncommitted at the BrowserStack. To do so select the needed combinations from the selection list using. Step 7. Copy and replace the platforms object in thebrowserstack.ymlfile like below. platforms: This is for go the test cases on 3 combinations. If you care to run merely on a single device you may edit the platforms accordingly. Step 8. Install BrowserStack plugin in Eclipse via MarketPlace. Step 9. Add the XPathTest program under src/test/java pamphlet and com.browserstack parcel. This family should extend SeleniumTest as it has the apparatus and teardown methods. Step 10. Run ChromeTest as TestNG test and view the test resolution on Automate dashboard. Dynamic XPaths in Selenium helps to make full-bodied test automation playscript that are lively and do not break even when DOM construction or element ’ s attribute changes. To make it more racy and efficient, follow below best practices while creating and using active XPath. 1. Avoid absolute and use relative XPath: Absolute XPath is extremely dependant on the construction of the DOM and if the structure modification, it will break and hence makes it less effective. Relative XPath are more pliable and full-bodied which get it more preferable than out-and-out XPath. 2. Use contains () for dynamic property values: Use contains () function to fit a part of the attribute value for dynamic element. This ensures that even if the attribute value changes, it will find the factor based on the unchanging attribute value. 3. Always examination XPath in browser console: It is always a good practice to test your XPath in browser ’ s inspect window to ensure its singularity before using it in the Selenium script. This helps catch invalid XPath early, kinda than finding them only when the Selenium script fails. 4. Avoid hard coded power: Indexing in XPath depends on the precise position of the element in the DOM which do it delicate. You should use other attribute or text to uniquely site the element through XPath. Avoid and use is a powerful cloud based platform that streamline web and mobile app testing by running Selenium tests across real browser and device. Here are the key benefits: Mastering dynamic XPaths in Selenium is crucial for building robust and flexible automation script. By leveraging techniques like contains (), starts-with (), and using variables, testers can effectively handle factor with changing dimension. You can use different methods to create dynamic Xpaths in Selenium. By following best practices like using proportional xpath over absolute xpath and testing xpath in browser console, it can help locate dynamic elements better. This access raise script reliability, making it adaptable to frequent UI changes, ultimately ameliorate the efficiency and maintainability of test automation. Mastering dynamic XPaths in Selenium streamlines the testing process and contributes to delivering high-quality package that converge user expectations. Effective use of locator is key to ensuring accurate and efficient machine-driven tests. On This Page # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Mastering Dynamic XPath in Selenium
What is XPath and Why is it Important in Selenium?
Syntax for XPath
XPath=//tagname [@ attribute='value ']
//a [@ title='Free Trial ']
Why XPath is important in Selenium
/html/body/div/div [2] /span/a
//button [@ id= ’ cancel ’]
//a [contains (@ course, ‘ heading ’) and contains (@ aria-label, ‘ logo ’)]
Understanding Dynamic XPath
Dynamic XPath vs Static XPath
Criteria Static XPath Dynamic XPath Definition Static XPath refers to the absolute path of elements which starts from the stem of the DOM. It is base on the element & # 8217; s ascribe that do not change during the test execution. Dynamic XPath is generally used to handle elements whose property may change at the clip of execution. Type of XPath Absolute XPath Relative XPath Flexibility Static XPath is less flexible as it may break in case of DOM construction change or attribute value change. Dynamic XPath is more flexible and adaptable to changes in the DOM structure as it is ground on the element & # 8217; s assign that are less likely to change. Readability Static XPaths are hard to say and understand as for some element which are towards the end of the DOM, the XPath gets very long and complex. Dynamic XPaths are easy to read and understand as it consist of the exact tag gens of the component and the attribute value. Syntax Single forward slash & # 8220; / & # 8221; is expend to denote the static XPath which entail you can choose the element from the root node. Double forwards slash & # 8220; // & # 8221; is used to denote dynamic XPath, which commence from the current node. Example /html/body/div/div [2] /span/a //button [@ id= ’ natural ’] Advantages of Using Dynamic XPath in Web Automation
//a [contains (@ aria-label, ‘ logo_ ’)]
Getting Started with XPath in Selenium
//button
//button [@ id= ’ submit ’]
//button [text () ='Register ']
//input [contains (@ id, 'password ')]
//a [starts-with (@ title, 'Free ')] //a [ends-with (@ title, 'Free ')]
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class XPathLocator {public static void primary (String args []) {WebDriver driver; driver = new ChromeDriver (); driver.get (`` https: //www.browserstack.com/ ''); WebElement freeTrial = driver.findElement (By.xpath(`` //a [@ title='Free Trial '] '')); freeTrial.click (); driver.quit ();}}Different ways to create Dynamic XPath in Selenium: Examples
/html/body/div [2] /header/div [1] /div/div/div/div/div [2] /div [3] /a
//a [@ title='Free Trial ']
// & lt; tagname & gt; [@ attribute_name='attribute_value '] or // * [@ attribute_name='attribute_value ']
//a [@ aria-label='Logo '] or // * [@ aria-label='Logo ']
// & lt; tagname & gt; [@ attribute_name1='attribute_value1 '] [@ attribute_name2='attribute_value2 '] or // * [@ attribute_name1='attribute_value1 '] [@ attribute_name2='attribute_value2 ']
//a [@ title='Free Trial '] [@ aria-label='Free Trial '] or // * [@ title='Free Trial '] [@ aria-label='Free Trial ']
//a [@ title='Free Trial ' and @ aria-label='Free Trial '] //a [@ title='Free Trial ' or @ aria-label='Free Trial ']
//button [contains (@ id, ‘ submit_ ’)]
//span [text () ='Free Trial ']
//a [starts-with (@ title, 'Free ')]
//a [ends-with (@ title, 'Free ')]
//span [contains (text (), 'Free ')]
//a [@ class='bstack-mm-logo '] //img
& lt; div & gt; & lt; div & gt; & lt; img & gt; Selenium & lt; /img & gt; & lt; /div & gt; & lt; /div & gt;
//img [@ class='logo '] /ancestor: :div
//div [@ id= ’ header-habitat ’] /descendant: :img
& lt; div & gt; & lt; button & gt; Java & lt; /button & gt; & lt; /div & gt; & lt; div & gt; & lt; button & gt; Python & lt; /button & gt; & lt; /div & gt;
//div [@ id='lang1 '] /following: :button
//div [@ id='lang2 '] /preceding: :button
Locating Web Elements with Dynamic XPath in Selenium
- os: Windows osVersion: 10 browserName: Chrome browserVersion: latest - os: OS X osVersion: Monterey browserName: Safari browserVersion: 15.6 - deviceName: iPhone 13 osVersion: 15 browserName: Chromium deviceOrientation: portrait
public class XPathTest extendsSeleniumTest {WebDriver driver =newChromeDriver (); @ Test (priority = 1, description = `` Verify BrowserStack page title '')public voidverifyBSLogo () {driver.get (`` https: //www.browserstack.com/ ''); driver.findElement (By.xpath(`` //a [@ class='bstack-mm-logo ' and contains (@ title, 'BrowserStack Logo ')] '')) .click (); Assert.assertEquals(driver.getCurrentUrl (), `` https: //www.browserstack.com/ '');} @ Test (antecedence = 2, description = `` Verify Get Started for Free pawl '')public voidclickGetStartedForFree () {driver.get (`` https: //www.browserstack.com/ ''); driver.findElement (By.xpath(`` //a [contains (@ id, 'signupModalProduct ')] '')) .click (); Assert.assertTrue(driver.getCurrentUrl () .contains (`` users/sign_up ''));}}Best Practices for Dynamic XPath Selenium
“ //div [2] /button [1] ”
“ //div [@ class='overlay '] //button [@ class='reset '] ”
Why run Selenium Tests on Real Devices?
Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously