XPath axes (parent, following-sibling, preceding) in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import static org.junit.jupiter.api.Assertions.*; public class XPathAxesTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("http://example.com/tablepage"); // Wait for the table cell with text 'Row 2' in first column WebElement cellRow2 = wait.until(ExpectedConditions.presenceOfElementLocated( By.xpath("//table//td[text()='Row 2']") )); // Find parent row of this cell using parent axis WebElement parentRow = cellRow2.findElement(By.xpath("parent::tr")); assertNotNull(parentRow, "Parent row should not be null"); // Find following sibling row using following-sibling axis WebElement followingSiblingRow = parentRow.findElement(By.xpath("following-sibling::tr[1]")); String followingSiblingText = followingSiblingRow.findElement(By.xpath("td[1]")).getText(); assertEquals("Row 3", followingSiblingText, "Following sibling row first column text should be 'Row 3'"); // Find preceding row using preceding axis WebElement precedingRow = parentRow.findElement(By.xpath("preceding-sibling::tr[1]")); String precedingRowText = precedingRow.findElement(By.xpath("td[1]")).getText(); assertEquals("Row 1", precedingRowText, "Preceding row first column text should be 'Row 1'"); System.out.println("Test passed: XPath axes navigation works correctly."); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the manual test case.
First, it opens the target URL and waits explicitly for the table cell containing 'Row 2' to appear.
Then it uses the parent::tr XPath axis to find the row containing that cell.
Next, it finds the following sibling row using following-sibling::tr[1] and verifies the first column text is 'Row 3'.
Similarly, it finds the preceding sibling row using preceding-sibling::tr[1] and verifies the first column text is 'Row 1'.
Assertions ensure the test fails if any expected condition is not met.
Finally, the driver quits to close the browser.
Now add data-driven testing with 3 different row texts: 'Row 2', 'Row 3', and 'Row 4' to verify their parent, following sibling, and preceding sibling rows.