Mastering XPath Part 2 1738694252
Mastering XPath Part 2 1738694252
2 Xpath
in Selenium
PART 2
Kalboussi Karim
Recap from Part 1
XPath basics: absolute, relative,
and exact XPath.
Importance of mastering XPath for
Selenium automation.
Kalboussi Karim
Locating Elements by
Tag Name and Attribute
Syntax :
.
//tagName[@attributeName='value']
Example :
Locating a username input field:
.
//input[@id='txtUsername']
.
//input[@name='txtUsername']
Kalboussi Karim
Locating Elements
with Exact Visible Text
Syntax :
.
//tagName[text()='exact text']
.
//*[text()='exact text']
Example :
Locating a hyperlink:
.
//a[text()='Pragmatic']
.
//*[text()='Pragmatic']
Kalboussi Karim
Locating Elements with
Partial Visible Text
Syntax :
.
//tagName[contains(text(),'substring')]
.
//tagName[contains(.,'substring')]
.
//*[contains(text(),'substring')]
Example :
.
//a[contains(text(),'Pragmatic')]
.
//*[contains(text(),'Test')]
Kalboussi Karim
Locating Elements by
Static Prefix of Visible Text
Syntax :
.
//tagName[starts-with(text(),'Prefix')]
.
//*[starts-with(text(),'Prefix')]
Example :
.
//a[starts-with(text(),'Prag')]
.
//*[starts-with(text(),'Prag')]
Kalboussi Karim
Locating Input Elements
with Visible Text
Syntax :
.
//tagName[@value='visibleText']
Example :
.
//input[@value='Karim']
Tip :
Use attribute values for input elements
rather than relying on inner text.
Kalboussi Karim
Locating Elements with
Multiple Attributes
Syntax :
.
//tagName[@attr1='value1'][@attr2='value2']
.
//tagName[@attr1='value1' and @attr2='value2']
Example :
.
//*[@type='submit'][@value='LOGIN']
Kalboussi Karim
Locating Elements with
Dynamic Attribute Values
Syntax :
.
//tagName[contains(@attributeName,'substring')]
.
//tagName[starts-with(@attributeName,'prefix')]
Example :
.
//a[contains(@href,'pragmatic')]
.
//*[starts-with(@href,'pragmatic')]
Kalboussi Karim
Validating XPath Syntax
Why Validate XPath?
Ensures correctness before execution.
Avoids runtime errors.
How to Validate:
Use browser developer tools
(Chrome/Firefox).
Plugins like XPath Helper or
SelectorsHub.
Kalboussi Karim
Best Practices for
Advanced XPath Usage
1. Keep it Simple: Use the shortest path
possible.
2. Be Specific: Use unique attributes to
avoid ambiguities.
3. Validate Regularly: Test your XPath
expressions frequently during
development.
4. Combine Strategies: Mix techniques
for dynamic and static elements when
needed.
Kalboussi Karim
summary
Advanced XPath techniques allow
precise, dynamic, and efficient element
location.
Combine multiple attributes, partial
matches, and prefix/suffix strategies for
flexibility.
Validate XPath expressions for accuracy
and robustness.
Karim Kalboussi
[email protected]