Careeroza
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
| Axis | XPath for the table above | Finds |
|---|---|---|
parent | //td[text()='ORD-1002']/parent::tr | the row of order 1002 |
following-sibling | //td[text()='ORD-1002']/following-sibling::td[1] | its status: Shipped |
preceding-sibling | //td[text()='Shipped']/preceding-sibling::td | the order id cell |
ancestor | //a[@href='/orders/1002']/ancestor::table | the whole table |
descendant | //table[@id='orders']/descendant::a | all 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