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

driver.findElement(By.xpath("//input[@id='lastName']//following::input[@type='radio'][1]")).click();

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

driver.findElement(By.xpath("(//div[@class='login-form']//child::input[@type='text'])[1]")).sendKeys("test");

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

driver.findElement(By.xpath("//button[@type='submit']//preceding::input[10]")).sendKeys("password");

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

driver.findElement(By.xpath("(//*[@class='login-form']//descendant::input)[1]")).sendKeys("first");

 

Share

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. Required fields are marked *

error: Content is protected !!