XPath axes help you find elements related to a known element in a web page. They make locating elements easier when you know their position relative to others.
0
0
XPath axes (parent, following-sibling, preceding) in Selenium Java
Introduction
When you want to find the parent element of a known child element.
When you need to locate a sibling element that comes after the current element.
When you want to find a sibling element that comes before the current element.
Syntax
Selenium Java
xpath_expression/axis_name::node_test
Replace axis_name with parent, following-sibling, or preceding-sibling.
node_test usually specifies the tag name or * for any node.
Examples
Selects the parent
div of the element with id 'child'.Selenium Java
//div[@id='child']/parent::divSelects all
li elements that come after the current li with class 'item' on the same level.Selenium Java
//li[@class='item']/following-sibling::liSelects all
input elements that come before the span with class 'label' on the same level.Selenium Java
//span[@class='label']/preceding-sibling::input
Sample Program
This Java Selenium code opens a test page, finds a child element by ID, then uses XPath axes to find its parent, following sibling, and preceding sibling elements. It prints their tag names or IDs.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class XPathAxesExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/testpage"); // Find child element WebElement child = driver.findElement(By.id("childElement")); // Find parent of the child element WebElement parent = child.findElement(By.xpath("parent::div")); System.out.println("Parent tag name: " + parent.getTagName()); // Find following sibling of the child element WebElement followingSibling = child.findElement(By.xpath("following-sibling::div")); System.out.println("Following sibling id: " + followingSibling.getAttribute("id")); // Find preceding sibling of the child element WebElement precedingSibling = child.findElement(By.xpath("preceding-sibling::div")); System.out.println("Preceding sibling id: " + precedingSibling.getAttribute("id")); } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Always ensure the XPath axes match the actual HTML structure to avoid errors.
Using axes can make your locators more flexible and robust when element positions change.
Summary
XPath axes help navigate between related elements in the page.
Common axes are parent, following-sibling, and preceding-sibling.
They improve locating elements when direct attributes are missing.