Friday, August 23, 2013

selenium xpath ancestor example

The below codes explains how to use xpath ancestor in your selenium code. I wrote code snippet here in java programming language.
import org.openqa.selenium.By;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumAncestorEx2 {
 public static void main(String[] args) {
  WebDriver driver = new FirefoxDriver();
  driver.get("file:///D:\\ancestor.html");
  WebElement element = driver.findElement(By
    .xpath("//div[@id='div4']"));
  String id=element.getAttribute("id"); 
  System.out.println("required element id" + id); 
  element = element.findElement(By.xpath("./ancestor::div[1]")); 
  System.out.println("above one level the parent element id of id \""+id +"\" is :"+element.getAttribute("id"));
  id=element.getAttribute("id"); 
  element = element.findElement(By.xpath("./ancestor::div[1]")); 
  System.out.println("above one level the parent element id of id \""+id +"\" is :"+element.getAttribute("id"));
  id=element.getAttribute("id"); 
  element = element.findElement(By.xpath("./ancestor::div[1]")); 
  System.out.println("above one level the parent element id of id \""+id +"\" is :"+element.getAttribute("id"));
  element = driver.findElement(By.xpath("//div[@id='div4']"));
  id=element.getAttribute("id");
  element = element.findElement(By.xpath("./ancestor::div[3]"));
  System.out.println("outer most parent div element id of id \""+id +"\" is :"+element.getAttribute("id"));
  
 }  
}

<html>
<body>
<div id="div1">
<div id="div2">
<div id="div3">
<table>
<tr>
<td>
<div id="div4">Ancestor Check</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</body>
</html>
you can save the above html content as ancestor.html and refer that in above java code.
Output:
above one level the parent element id of id "div4" is :div3
above one level the parent element id of id "div3" is :div2
above one level the parent element id of id "div2" is :div1
outer most parent div element id of id "div4" is :div1
You can also refer basic example of ancestor in below link
http://softwares-list.blogspot.in/2013/08/selenium-xpath-ancestor-example.html

1 comment:

  1. I never tried with approach of getting ancestor element by specifying parent position, thank you so much for this example.It worked well.

    ReplyDelete