How to handle dynamic web tables/HTML tables in Selenium webdriver using java?.

Please copy the below is the sample code for Table and make an html file.
<!DOCTYPE html>
<html>
<head>
<style>
tbody {color:red;}
table, th, td { border: 1px solid black;}
</style>
</head>

<body>
<p>Dynamic Table elements</p>

<p><b>Tip:</b> The tbody elements will not affect the layout of the table by default. However, you can use CSS to style these elements.</p>

<table>
  <tbody>
    <tr>
      <td>2014</td>
      <td>January</td>
      <td>$100</td>
      <td>Tk.8000</td>
    </tr>
        </tr>
        <tr>
      <td>April</td>
      <td>$50</td>
    </tr>
    <tr>
     <td>2015</td>
      <td>February</td>
      <td>$80</td>
      <td>Tk.6400</td>
    </tr>
        <tr>
      <td>March</td>
      <td>$60</td>
      <td>Tk.4800</td>
    </tr>
  </tbody>
</table>
</body>
</html>
 

Java Code



 import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Dynamictablehandler {  
   public static void main(String[] a) throws InterruptedException {  
     // Initialize Web driver    
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window    
     driver.manage().window().maximize();  
     //Go to Page    
     driver.get("file:///F:/table.html");  
     //get the entire html table and store this in a variable   
 WebElement table = driver.findElement(By.xpath("html/body/table/tbody"));  
     //Get all the rows  
 List<webelement> rows = table.findElements(By.tagName("tr"));  
     for (int r = 0; r < rows.size(); r++) {  
       //Get all the columns in every row  
 List<WebElement> columns = rows.get(r).findElements(By.tagName("td"));  
       for (int col = 0; col < columns.size(); col++) {  
 System.out.print(columns.get(col).getText().trim() + "  ");  
       }  
       System.out.println();  
     }  
     driver.quit();  
   }  
 }  

1 comment:

  1. Hello author,

    I found your blog while searching for the updates in Selenium WebDriver,I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about Selenium Tutorials from basics with reference of your blog.

    ReplyDelete