XPath Axes in Selenium

In Selenium, if you are not able to find elements using the general locators like Id, Name, TagName, etc.. then XPath axes can be used to find these complex or dynamic elements on the web-page.  XPath axes represents a relationship to the current node, and is used to locate nodes relative to that node on the tree.

1. Following: Selects everything in the document after the closing tag of the current node


2. Ancestor: Selects all ancestors (parent, grandparent, etc.) of the current node

WebElement element = driver.findElement(By.xpath("//a[contains(text(),'Sign')]//ancestor::div[2]"));

3. Child: Selects all children of the current node


4. Preceding: Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes


5. Following-sibling: Selects all siblings after the current node

driver.findElement(By.xpath("//p[text()='Already have account ? ']//following-sibling::a")).click();

6. Parent: Selects the parent of the current node 

WebElement element = driver.findElement(By.xpath("//p[text()='Already have account ? ']//parent::div"));

7. Descendant: Selects all descendants (children, grandchildren, etc.) of the current node




Bijan Patel

Founder & Creator of QAScript | 12+ years of IT Experience | Full Stack Automation Engineer | Blogger | Trainer

You may also like...

Leave a Reply

Your email address will not be published.