Thursday, August 22, 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.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumAncestorEx {
 public static void main(String[] args) {
  WebDriver driver = new FirefoxDriver();

  driver.get("file:///D:\\ancestor.html");
  WebElement element = driver.findElement(By
    .xpath("//div[@id='innerDiv1']"));

  System.out.println("inner element id" + element.getAttribute("id"));
  element = element.findElement(By.xpath("./ancestor::div[@id='div1']"));
  System.out.println("ancestor element id  : " + element.getAttribute("id"));
 }
}
<html>
<body>
 <div id="div1">
  <table>
   <tr>
    <td>
     <div id="innerDiv1">Ancestor Check</div>
    </td>
   </tr>
  </table>
 </div>
</body>
</html>
you can save the above html content as ancestor.html and refer that in above java code. After running the above program and observing the output, you can clearly understand the usage.

No comments:

Post a Comment