Relative XPath Fundamentals
Master relative XPath techniques including single attributes, logical operators, text methods, and advanced XPath functions for robust element location.
Relative XPath Overview
Why Relative XPath?
Relative XPath is used to locate elements in web pages and is the most preferable XPath method because we can start searching elements from the middle of the HTML DOM structure.
🔑 Key Characteristics
- • Starts with double forward slash (//)
- • More flexible than absolute XPath
- • Has different inbuilt methods and keywords
- • Can start searching from any point in DOM
- • Most robust and maintainable approach
Basic Syntax Structure
//tagname[@attribute='value']
XPath Location Methods
1. Single Attribute XPath
Syntax
Examples:
Facebook Registration Form
Form Elements
2. XPath with AND Operator
Condition
Both attribute values should exist in the same element
Syntax
Examples:
3. XPath with OR Operator
Condition
Any one attribute value should exist in the same element
Syntax
Examples:
Text-Based XPath Methods
4. text() Method
Use Case
Locate elements using their physical text content (buttons, labels, links)
Syntax
Examples:
5. starts-with() Method
Use Case
Locate elements when starting value is constant and remaining value is dynamic
Syntax
Examples:
6. contains() Method
Use Case
Locate elements using partial text values (any part of the text)
Syntax
Examples:
Comparison Example
7. normalize-space() Method
Use Case
Removes extra spaces (starting, middle, ending) and ignores case sensitivity
Syntax
Examples:
Practical Implementation
Java Implementation Example
Facebook Registration Form
Locating month dropdown using different XPath approaches
WebElement monthDropdown1 = driver.findElement(By.xpath("//select[@name='birthday_month']"));
WebElement monthDropdown2 = driver.findElement(By.xpath("//select[@aria-label='Month']"));
WebElement monthDropdown3 = driver.findElement(By.xpath("//select[@id='month']"));
// Using AND operator for more specific targeting
WebElement loginBtn = driver.findElement(By.xpath("//input[@type='submit' and @class='submit-button btn_action']"));
// Using text() method for buttons
WebElement submitBtn = driver.findElement(By.xpath("//button[text()='Submit']"));
// Using normalize-space for buttons with extra spaces
WebElement loginBtnNorm = driver.findElement(By.xpath("//button[normalize-space(text())='Login']"));