Selenium XPath

XPath stands for XML Path Language. It builds a path through the HTML structure to reach a specific element, similar to giving directions through a building using floor and room numbers.

Diagram: XPath As A Building Address

html
 |
 body
  |
  div (id="login")
   |
   input (id="email")

An absolute XPath for the input box reads as /html/body/div/input, walking down floor by floor from the top.

Absolute XPath

Absolute XPath starts from the root html tag using a single forward slash.

/html/body/div[1]/form/input[1]

This path breaks easily. Adding one new div anywhere above the target changes the entire path and fails the test.

Relative XPath

Relative XPath starts anywhere in the document using a double forward slash. Most real projects use relative XPath because it survives small page changes.

//input[@id='email']

This line searches the whole page for any input tag with an id attribute equal to email, regardless of its position.

XPath With Attributes

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

This finds a button tag where the class attribute equals submit-btn exactly.

XPath Functions

contains()

Matches an attribute that contains a given piece of text, useful when class names include multiple words or dynamic values.

//div[contains(@class, 'product')]

starts-with()

Matches an attribute that begins with given text, useful for IDs that change slightly on each page load.

//input[starts-with(@id, 'user_')]

text()

Matches an element based on its visible text content.

//a[text()='Sign In']

Combining Conditions

XPath supports and/or logic to match multiple conditions at once.

//input[@type='text' and @name='username']

This line finds an input tag that is both type text and named username.

Navigating Parent And Sibling Elements

Parent Axis

//span[text()='Error']/parent::div

This finds the div that directly contains a span showing the word Error.

Following-Sibling Axis

//label[text()='Email']/following-sibling::input

This finds the input box placed right after a label showing the word Email, common in form layouts.

Practical Example

Imagine a table listing course names and prices. To click the price next to a course named Selenium Basics, XPath combines text matching with sibling navigation.

//td[text()='Selenium Basics']/following-sibling::td[1]

This locates the table cell right after the cell that says Selenium Basics, grabbing its price value.

Leave a Comment

Your email address will not be published. Required fields are marked *