Selenium WebDriver - Fetch/Read Table Data


Following Script will extract data from table:


public class table {

 WebDriver driver = new FirefoxDriver();

 @BeforeTest
 public void setup() throws Exception {
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
  driver.get("https://www.techlistic.com/p/demo-selenium-practice.html");
 }

 @AfterTest
 public void tearDown() throws Exception {
  driver.quit();
 }

 @Test
 public void print_data(){
 //Get number of rows In table.
 int Row_count = driver.findElements(By.xpath("//*[@id='post']/div[1]/table/tbody/tr")).size();
 System.out.println("Number Of Rows = "+Row_count);

 //Get number of columns In table.
 int Col_count = driver.findElements(By.xpath("//*[@id='post']/div[1]/table/tbody/tr[1]/td")).size();
 System.out.println("Number Of Columns = "+Col_count);

 //divided xpath In three parts to pass Row_count and Col_count values.
 String first_part = "//*[@id='post']/div[1]/table/tbody/tr[";
 String second_part = "]/td[";
 String third_part = "]";

 //Used for loop for number of rows.
 for (int i=1; i<=Row_count; i++){
  
  //Used for loop for number of columns.
  for(int j=1; j<=Col_count; j++){
   
   //Prepared final xpath of specific cell as per values of i and j.
   String final_xpath = first_part+i+second_part+j+third_part;
   
   //Will retrieve value from located cell and print It.
   String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
   System.out.print(Table_data +" ");
  }

  System.out.println("");
  System.out.println("");
  }
 }
}


Console output of above given example will looks like bellow.

Number Of Rows = 3
Number Of Columns = 6
11  12  13  14  15  16  

21  22  23  24  25  26  


31  32  33  34  35  36

Feel free to share your thoughts in comments or email me. Happy Coding :)


Actions Class- Mouse Events  << Previous   ||   Next >>   Handle Dynamic Xpaths (Dynamic Table)

Refer Selenium Webdriver Tutorials Series



Author: Vaneesh Behl

Join Telegram channel of this blog at https://t.me/techlisticspace


Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

  1. Hi,

    While using the link "https://www.techlistic.com/p/sample-table.html"given above is not working..It shows message as "Sorry, the page you were looking for in this blog does not exist."

    ReplyDelete
    Replies
    1. Hi, Thanks for reporting this issue. Now, issue has been fixed. URL has been changed and you can access it. Thanks!

      Delete

Post a Comment

Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate 'User Registration' of E-commerce Website using Selenium

Selenium WebDriver Browser and Navigation Commands

Automate 'Buy Product' from E-commerce Website using Selenium