Mastering XPath
Mastering XPath
Xpath
in Selenium
PART 1
Kalboussi Karim
What is XPath?
XPath (XML Path Language) is a
query language used to locate
nodes in an XML document.
Kalboussi Karim
Types of XPath
Absolute XPath
Relative XPath
Exact XPath
XPath
Kalboussi Karim
Xpath Importance
XPath enables precise element
location even in complex DOM
structures.
It supports dynamic content
handling, which is common in
modern web applications.
XPath provides flexible options
for element selection
using attributes,
hierarchy, and more.
Kalboussi Karim
What is Absolute XPath?
-Absolute XPath specifies the full path
from the root node to the target element.
-Key Characteristics:
Starts with a single /.
Breaks easily with DOM changes.
-Syntax Example:
/html/body/div/header/nav/ul/li[2]
Kalboussi Karim
What is Relative XPath?
-Relative XPath starts from a specific
node in the DOM, not the root node.
-Key Characteristics:
Starts with //.
More robust to DOM changes.
-Syntax Example:
//nav/ul/li[@class='menu-item'][3]
Kalboussi Karim
What is Exact XPath?
-Exact XPath refers to techniques or
conditions ensuring precise identification
of elements.
-Key Characteristics:
Utilizes specific attributes (id, class, etc.).
Combines with logical operators.
Ideal for identifying dynamic elements.
-Syntax Example:
//button[contains(@class, 'submit') and @type='submit']
Kalboussi Karim
Absolute vs Relative XPath
Aspect Absolute XPath Relative XPath
Starts with / //
Kalboussi Karim
Examples of XPath Usage
1. Absolute XPath Example:
/html/body/div/main/section/article[1]/h1
Locates the first <h1> tag in the first <article>
in the section.
Kalboussi Karim
When to Use Absolute XPath?
Use Absolute XPath:
When working with simple, static pages.
For quick tests where DOM changes are
unlikely.
Kalboussi Karim
When to Use Relative or
Exact XPath?
Use Relative XPath:
For complex, dynamic pages.
When flexibility and robustness are
critical.
Kalboussi Karim
summary
XPath is a powerful tool for locating
elements in Selenium.
Absolute XPath provides full paths but
lacks flexibility.
Relative and Exact XPaths offer dynamic
and precise solutions.
Karim Kalboussi
[email protected]