XPath axes for test automation - axis types and syntax

XPath axes for test automation - axis types and syntax

There is a fair number of different axes in the XPath specification. An axis represents a relationship to the context node, and is used to locate nodes relative to that node on the tree. Let's review some XPath selector axes that are often used in test automation:

1) ancestor::

//*[ancestor::*[contains(@class, "product-item")]]

XPath axis ancestor - selects all ancestors (parent, grandparent, ...) of the current node.

2) descendant::

//*[descendant::*[contains(@class, "product-item")]]

XPath axis descendant - selects all descendants (children, grandchildren, ...) of the current node.

XPath selector examples

Here is an example of a real-life long XPath selector:

//*[ancestor::*[contains(@class, "product-item")] and contains(@class, "actual-price") and contains(text(), "some test text")]

You can test it by opening browser console and running:

$x('//*[ancestor::*[contains(@class, "product-item")] and contains(@class, "actual-price") and contains(text(), "some test text")]');