Friday, 14 February 2014

How to get the data in table cell using selenium webdriver in Java?

Selenium webdriver provides one method called - getText() which can be used to read the innertext of any web element not just table cell in Selenium Webdriver in Java.

String actualValue = c.getText();
above code will return the data displayed in cell c in selenium webdriver.

Full example in Java with selenium webdriver

package temp;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class first {

public static void main(String[] args) {
              // TODO Auto-generated method stub

System.setProperty("webdriver.chrome.driver""C:\\Selenuim\\chromedriver2.3.exe");
WebDriver driver =  new ChromeDriver();

try{
driver.get("http://register.rediff.com/register/register.php");

Thread.sleep(2000);
WebElement e = driver.findElement(By.tagName("td"));

String actualValue = e.getText();


       System.out.println("Text displayed in the first td -> " + actualValue);
      
Thread.sleep(2000);

}

catch(Exception ex){
       System.out.println("Exception " + ex.getMessage());
              }
              finally{
                    
                     driver.close();
                     driver.quit();
              }
       }

}


Please note that we can get the text inside other web elements  like button, checkbox, radiobutton, checkbox, combobox in similar way using getText method in Java using selenium webdriver.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

2 comments:

  1. Thank you for the above. I would like to get to the 2nd column in the row i tried
    WebElement e = driver.findElement(By.tagName("td[2]")); but this does not work.

    Any suggestions?

    ReplyDelete
    Replies
    1. The syntax you are using is not correct. tagname should not contain any numbers.

      To get the the value from the cell with row r and column c, you will have to use for loop. Here are the steps.
      1. First find the nth row element using any of the element identification methods.
      2. Then find all td elements in that row using tagName method.
      3. Then use for loop to get the nth cell in that td elements.

      Delete

Buy Best Selenium Books

Contributors