XPath Axes

Moving Around the DOM

Sometimes the element you want has no good attribute, but a neighbour does. Axes let XPath move up, down or sideways.

<table id="orders">
  <tr><td>ORD-1001</td><td>Delivered</td><td><a href="/orders/1001">View</a></td></tr>
  <tr><td>ORD-1002</td><td>Shipped</td><td><a href="/orders/1002">View</a></td></tr>
</table>

Common Axes

AxisXPath for the table aboveFinds
parent//td[text()='ORD-1002']/parent::trthe row of order 1002
following-sibling//td[text()='ORD-1002']/following-sibling::td[1]its status: Shipped
preceding-sibling//td[text()='Shipped']/preceding-sibling::tdthe order id cell
ancestor//a[@href='/orders/1002']/ancestor::tablethe whole table
descendant//table[@id='orders']/descendant::aall View links

Example

String status = driver.findElement(
        By.xpath("//td[text()='ORD-1002']/following-sibling::td[1]")).getText();
driver.findElement(By.xpath("//td[text()='ORD-1002']/following-sibling::td/a")).click();
System.out.println("Status was " + status + ", now at " + driver.getCurrentUrl());

Example

Output:

Run OrderStatusTest.main()

Example output

Status was Shipped, now at https://shopease.example.com/orders/1002