Examples of Relative and Absolute XPath in Selenium
1. Relative XPath:
Suppose we want to locate the “Search” input field within the navigation bar of a webpage. The Relative XPath expression could be:
//img[@class='gfg_logo_img']
This XPath starts from the ‘nav‘ element and searches for the input field with the id “search” within it. It’s flexible because it doesn’t depend on the exact position of the navigation bar within the document.
Example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
public class Xpath_Selection {
public static void main(String[] args) {
System.setProperty("webdriver.firefox.marionette", "C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.stqatools.com");
// Relative xpath
driver.findElement(By.xpath("//img[@class='gfg_logo_img']"));
}
}
Output:
2. Absolute XPath:
To find the same “Search” input field using an Absolute XPath expression:
//html[1]/body[1]/nav/div/a[2]
This Absolute XPath specifies the full path from the root of the HTML document to the input field. It relies on the exact structure of the webpage, making it longer and more prone to breaking if the structure changes.
Example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;
public class Xpath_Selection {
public static void main(String[] args) {
System.setProperty("webdriver.firefox.marionette", "C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.w3wiki.org");
// Absolute xpath
driver.findElement(By.xpath("/html[1]/body[1]/nav/div/a[2]"));
}
}
Output:
Difference between Relative and Absolute XPath in Selenium
XPath is important for element location in Selenium automation. With flexibility, Relative XPath navigates elements according to how they relate to other elements. While absolute XPath offers greater precision, it makes scripts larger and less flexible because it provides the entire path from the HTML document’s root. Comprehending the differences between Absolute and Relative XPath is essential to effective automated programming. This article explores their differences and advises when to use each technique for reliable Selenium automation.
Table of Content
- Relative XPath in Selenium
- Advantages of Relative XPath
- Disadvantages of Relative XPath
- Absolute XPath in Selenium
- Advantages of Relative XPath
- Disadvantages of Relative XPath
- Choosing the Right XPath Strategy
- Examples of Relative and Absolute XPath in Selenium
- 1. Relative XPath:
- 2. Absolute XPath:
- Best Practices for Writing XPaths
- Best Practices for Relative XPath:
- Best Practices for Absolute XPath:
- Related Articles:
- Conclusion
- FAQs on Difference between Relative and Absolute XPath in Selenium
Contact Us