"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

January 01, 2011

Selenium Xpath Looping Example

Thanks to author for article Selenium IDE with an XPath Locator. I wanted to try the same example using TestNG code.

Followed the below steps
1. Created Sample Test Page link
2. Create a project and add required libraries. Verify earlier post

Below is the Example Code - Working Code

import static org.testng.Assert.assertTrue;
import java.util.Vector;
import org.testng.Assert;
import org.testng.annotations.*;
import com.thoughtworks.selenium.*;
public class SeleniumXpath
{
     
public static Selenium selenium;

@BeforeTest
public void openBrowser()
{
      System.out.println("Before Test");
selenium = new DefaultSelenium("localhost", 4444, "*iehta","http://sqlandsiva.blogspot.com/2011/01/test-xml-page-for-selenium.html);
}

@Test
public void LoopthruElement()
{
try
{
      System.out.println("Running Test1");
      selenium.start();
      selenium.open("http://sqlandsiva.blogspot.com/2011/01/test-xml-page-for-selenium.html");
      int i=1,j=1;
      while(selenium.isElementPresent("//table[@id='firstTable']//tr["+i+"]/td["+j+"]"))
{
      while(selenium.isElementPresent("//table[@id='firstTable']//tr["+i+"]/td["+j+"]"))
                       
{
            System.out.println("Value is " + selenium.getText("//table[@id='firstTable']//tr["+i+"]/td["+j+"]"));
            j++;
      }
      j=1;
      i++;
}
}
catch(Exception ex)
{
                  ex.toString();
}
}
}

This is tested and working code. Run it as TestNG Test. I intend to add more examples in the page and improve on this example.

Happy Reading!!

No comments: