Quick Contact

    Identify Table Rows and Columns

    Web tables are a group of elements that are logically stored in a row and column format. It is used to organize similar information on a web page. The various tags defined in HTML table are:

    • ’table’ tag defines HTML table.
    • ‘tbody’ tag defines a container for rows and columns.
    • ‘tr’ defines rows in an HTML table.
    • ’td’/’th’ define the column of an HTML table.
    • <tag> for headings

    The diagram below shows the mapping of Table with HTML tags

    Excel sheet is a simple example of table structures. Each cell in the Excel sheet can be represented as <td> in the HTML table. The <td> elements are the data containers and these can contain all sorts of HTML elements like text, images, lists, other tables.

    Example of HTML table (first row is defined as header and later two rows are containing data).

         
    	      <table>
              <tbody>
              <tr>
                      <th>Automation Tool</th>
                      <th>Licensing</th>
                      <th>Market response</th>
              </tr>
              <tr>
                    <td>Selenium</td>
                    <td>Free</td>
                    <td>In</td>
              </tr>
              <tr>
                    <td>QTP</td>
                    <td>Paid</td>
                    <td>Out</td>
              </tr>
        </tbody>
        </table>	
    
    Process to Identify Table rows and columns

    The process to identify the Table rows and columns in selenium are:

    • Get the entire HTML table and store this in a variable ‘htmltable’ of type web element.
    • Get all the rows with tag name ‘tr’ and store all the elements in a list of web elements. Now all the elements with tag ‘tr’ are stored in ‘rows’ list.
    • Loop through each row and get the list of elements with tag ‘th’. ‘rows.get(0)’ will give first row and ‘findElements(By.tagName(“th”))’ will give list of columns for the row.
    • Iterate using ‘columns.getsize()’ and get the details of each cell.

    In Selenium there are two ways of Identifying Table Rows and Columns:

    • For Static tables: If a number of rows and columns are always constant,

      Below is the xpath of one of the cell in html table. Let’s say “firstname”

      //div[@id=’main’]/table[1]/tbody/tr[1]/th[1]

      Where, tr[1] defines first row and th[1] defines first column.

      Example:

      for(intnumberOfRows=1; numberOfRows<=5; numberOfRows++)
      {
                     for(intnumberOfCol=1; numberOfCol<=3; numberOfCol++)
                {
                     System.out.println(driver.findElement(By.xpath
                     (“//div[@id='main']/table[1]/tbody/tr [“+numberOfRows+”]/th[“+numberOfCol+”]”)));
                }
                }
      
    • For Dynamic Tables: If Number of rows and columns
      are NOT fixed.Example:

              	WebElementhtmltable=driver.findElement(By.xpath("//*[@id='main']/ 
                  table[1]/tbody"));
                  List<WebElement> 
                  rows=htmltable.findElements(By.tagName("tr"));
      
                  for(intrnum=0;rnum<rows.size();rnum++)
                  {
                  List<WebElement> 
                  columns=rows.get(rnum).findElements(By.tagName("th"));
                  System.out.println("Number of columns:"+columns.size()); 
                  for(intcnum=0;cnum<columns.size();cnum++)
                  {
                  System.out.println(columns.get(cnum).getText());
      
                  }
                  }
      
    Extracting Values from a Cell

    Selenium WebDriver provides method getText() which can be used to read the inner text of any web element. For example below line of code returns the data displayed in cell c in selenium WebDriver.

    Syntax

    String actualValue = c.getText();

    Example

         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\\chromed river2.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();
            }
          }
       }   
    
    Dynamically Identify Tables Data

    For identifying tables data dynamically follow the below mention sequence of steps:

    • Fetch no of rows in a tableOnce the table is located the next step is to iterate through it and count the number of rows &
      columns. Below code identifies all the rows & store it in the ‘rows’ list. Next we calculate the number of rows using size() method & store it in the ‘rows_count’ variable.

      List rows = Table.findElements(By.tagName("tr")); 
             rows_count = rows.size();
    • Fetch # of columns in a rowBelow code identifies all the columns in a row & store it in the ‘columns’ list. Next we calculate the number of columns using size() method & store it in the ‘col_count’ variable.
      List columns = rows.get(i).findElements(By.tagName("td")); 
              col_count = columns.size();
    • Iterate through the Web TableOuter loop iterates through all the rows one at a time and inner loop through all the columns (cells) within each row. getText() method is used to fetch a cell’s value.
      for(inti= 0; i<rows_count; i++){
                    List columns = rows.get(i).findElements(By.tagName("td")); 
                    col_count = columns.size();
                    for(int j=0; j< col_count; j++){ 
                    cellText = columns.get(j).getText(); 
                    System.out.print(cellText+"	");
           }
                    System.out.println("");
           }
      

      Example

               	importjava.util.List; 
               	importorg.openqa.selenium.By;
               	importorg.openqa.selenium.WebDriver;
               	importorg.openqa.selenium.WebElement;
               	importorg.openqa.selenium.chrome.ChromeDriver;
               	public class WebTable {
      
               	public static void main(String args[]){ 
               	introws_count,col_count;
               	String cellText = null;
      
               	//Navigate to the Web page
      
               	System.setProperty("webdriver.chrome.driver","Path to your chromedriver.exe");
      
               	WebDriver driver = new ChromeDriver();
               	driver.get("http://money.rediff.com/gainers/bsc/daily/gro upa?");
               	driver.manage().window().maximize();
      
               	//Identify the table 
      
               	WebElement Table =
                  driver.findElement(By.ByClassName.className("dataTable"));
      
                  //Read specific cell value 
      
                  WebElement cell =
                  driver.findElement(By.xpath("//table/tbody/tr[2]/td[3]"));
      
                  System.out.println("Data for Row 2 and Column 3 is "+cell.getText()+".");
                  //Fetch # of rows in a table
      
                  List rows = Table.findElements(By.tagName("tr")); 
                  rows_count = rows.size();
                  //Iterate through the rows 
                  for(inti= 0; i<rows_count; i++){
      
                  //Fetch # of columns in a row
      
                  List columns = 
                  rows.get(i).findElements(By.tagName("td"));
                  col_count = columns.size();
      
                  //Iterate through the columns within 
      
                  particular row 
                  for(int j=0; j< col_count; j++){
                           cellText = columns.get(j).getText();
                            System.out.print(cellText+"	");
                  }
                   System.out.println("");
      
              }
            }
           }
      
    CheckBox & Radio Button

    CheckBox & Radio Button Operations are easy to perform and most of the times the simple ID attributes work fine for both of these. But selection and d-selection is not the only thing which need with Check Boxes and Radio Buttons. It might like to check that if the Check Box is already checked or if the Radio Button is selected by default or anything. Check Boxes and Radio Button deals exactly the same way and it can perform below mentioned operations on either of them.

    Methods to Select Checkbox And Radio Button
      • Use ID For Selecting Checkbox/Radio Button.The ID attribute can be use to select a Radio Button or a CheckBox. The Webdriver command is here to click which can be apply to both types of elements
        // Java code example to select checkbox/radio button. 
                     WebElement target = driver.findElement(By.id("checkbox1"));
        
                     target.click();
        
      • Use IsSelected Method To Check The State Of Checkbox/Radio Button.

        If a Checkbox/Radio Button has selected/deselected and just check its final state. Then, use the
        <IsSelected> command to know that the correct status of the element.

        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 findElementsTest {
        public static void main(String[] args) throws Exception {
        // Launch browser
        WebDriver driver = new FirefoxDriver();
        // Maximize window driver.manage().window().maximize();
        // Navigate to the URL driver.get("http://www.techbeamers.com");
        // Sleep for 5 seconds Thread.sleep(5000);
        // Store all the elements of the same category in the
        //list of WebLements.
        List<WebElement> list = driver.findElements(By.name("radioButton"));
        
        
        // Create a boolean variable to store true/false. Boolean is_selected = list.get(0).isSelected();
        
        // If 'is_selected' is true that means the first radio
        //button is selected.
        if (is_selected == true) {
        
        
        // If the first radio button is selected by default
        //then, select the second radio button. list.get(1).click();
        
        } else {
        
        
        // If the first radio button is not selected then,
        //click the first radio button.
         
        
        list.get(0).click();
        }
        }
        }
        

    Note: When there is a group of Radio Buttons/Check Boxes on the page then, it is possible that
    their names are same, but values are different. That’s why it has used the Webdriver findElements
    command to get the list of web elements.

    • Use Element Value For Selecting Checkbox/Radio Button.

      One of the intuitive ways to select the Radio Buttons/Check Boxes is by toggling their Values. Please follow the below code example for more clarity.

      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 findElementsTest {
      public static void main(String[] args) throws Exception {
      // Launch browser
      
      WebDriver driver = new FirefoxDriver();
      // Maximize window driver.manage().window().maximize();
      
      // Navigate to the URL
      driver.get("http://www.techbeamers.com");
      // Sleep for 5 seconds Thread.sleep(5000);
      
      // Find the checkbox or radio button element by its name.
      
      List<WebElement> list = driver.findElements(By.name("checkbox"));
      
      // Get the number of checkboxes available. int count = list.size();
      
      // Now, iterate the loop from first checkbox to last c
      //checkbox.
      for (int i = 0; i < count; i++) {
      
      // Store the checkbox name to the string variable,
      
      //using 'Value' attribute
      String sValue = list.get(i).getAttribute("value");
      
      // Select the checkbox if its value is the same that
      //you want.
      
      if (sValue.equalsIgnoreCase("checkbox")) {
      
      list.get(i).click();
      
      // This statement will get you out of the for
      //loop. break;
      }
      }
      }
      }
      
    • Use CssSelector For Selecting Checkbox/Radio Button.

      Another easy way to select/deselect a checkbox or a radio button is by using the cssSelector. Please refer the below code snippet to bring more clarity.

      // Java example code to select a checkbox using the cssSelector.
      
              WebElement checkBox = driver.findElement(
              By.cssSelector("input[value='TechBeamers']"));
               checkBox.click();
      

    Example

    Below is the HTML code of the input form which you can save as an HTML file locally to practice the checkbox and radio button operations.

    <html>
    <head>
    <title>Perform Checkbox and Radio Button Operations.
    </title>
    </head>
    <body>
    <form name="testform" action="" method="POST">
    <div align="center">
    <br>
    <input type="checkbox" name="option-1" value="Java">Java
    <input type="checkbox" name="option-2" value="C++">C++
    <input type="checkbox" name="option-3" value="Python" checked>Python
    <input type="checkbox" name="option-4" value="PHP">PHP
    <input type="checkbox" name="option-5" value="CSharp">CSharp
    <input type="checkbox" name="option-6" value="Ruby">Ruby
    <input type="checkbox" name="option-7" value="Perl">Perl
    <br>
    <input type="radio" name="group-1" value="Programming"> Programming
    <input type="radio" name="group-1" value="Testing"> Testing
    <input type="radio" name="group-1" value="Test Automation" checked> Test Automation
    </div>
    </form>
    </body>
    </html>
    
    Select Class in Selenium

    Select is a class which is provided by Selenium to perform multiple operations on DropDown object and Multiple Select object. This class can be found under the Selenium’s
    Support.UI.Select package. Its object is created by a New keyword with regular class creation. Select class only works for elements with <select> tags.

    Syntax
    Select oSelect = new Select());

    Example

    WebElement element = driver.findElement(By.id("Country")); 
    Select oSelect = new Select(element);

    WebDriver Code using Selenium Select Class

    Create a new java class named as “HandlingDropDown” under any running project.

    Copy and paste the below code in the “HandlingDropDown.java” class.

    Below is the test script that is equivalent to the above-mentioned scenario

    import static org.junit.Assert.*; 
    import org.junit.After;
    import org.junit.Before; 
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.Select;
    
    /**
    *	class description
    
    */
    
    public class HandlingDropDown { WebDriver driver;
    
    /**
    * Set up browser settings and open the application
    */
    
    @Before
    public void setUp() {
    driver=new FirefoxDriver();
    
    // Opened the application
    driver.get("file:///F:/Work/Blogs/testingstuff/DemoWe bAlert.html");
    driver.manage().window().maximize();
    }
    
    
    /**
    *	Test to select the dropdown values
    *	@throws InterruptedException
    */
    
    
    @Test
    public void testSelectFunctionality() throws InterruptedException {
    
    
    // Go to google
    driver.findElement(By.linkText("Google")).click();
    
    
    // navigate back to previous webpage
    driver.navigate().back();
     
    
    Thread.sleep(5000);
    
    // select the first operator using "select by value" Select selectByValue = new
    Select(driver.findElement(By.id("SelectID_One"))); 
    selectByValue.selectByValue("greenvalue"); 
    Thread.sleep(5000);
    
    // select the second dropdown using "select by visible text"
    Select selectByVisibleText = new Select (driver.findElement(By.id("SelectID_Two")));
    selectByVisibleText.selectByVisibleText("Lime"); 
    Thread.sleep(5000);
    
    // select the third dropdown using "select by index" Select selectByIndex = new
    Select(driver.findElement(By.id("SelectID_Three"))); 
    selectByIndex.selectByIndex(2); Thread.sleep(5000);
    }
    
    /**
    *	Tear down the setup after test completes
    */
    
    
    @After
    public void tearDown() { driver.quit();
    
    }
    }
    
    Drop Down Handle

    A drop-down list is a graphical control element, similar to a list box which allows the user to choose one value from a list. When a drop-down list is inactive it displays a single value. When activated it displays a list of values from which the user may select one. When the user selects a new value the control reverts to its inactive state displaying the selected value. For handling dropdowns Selenium provides Select class that has some predefined method. There are three different ways by which dropdown values can be selected.

    • Select by index
    • Select by value
    • Select by visible
    Select Multiple Values from the List

    WebDriver provides a Select class to Select Multiple Values from the List. Lets understand with

    an example of below dropdown with four values.
        Maruti 
        Honda 
        BMW
        Toyota
    

    Option 1) if user wants to select the first two options from above drop down, then the code will be as below. The code will Select Maruti and Honda from a list.

    WebElementselectList= 
    driver.findElement(By.xpath("//select[@name='cars']"));
    Select select = new Select(selectList); 
    select.selectByVisibleText("Maruti");
    select.selectByVisibleText("Honda");
    

    Option 2) if user wants to select multiple options from drop down manually, he would press CTRL and click on all the options which he wants to select.In order to replicate the above method using automation webdriver provides Actions class to interact with Keyboard actions.

    WebElement option1= 
    driver.findElement(By.xpath("//option[@value='Maruti']"));
    WebElement option2= 
    driver.findElement(By.xpath("//option[@value='Honda']"));
    Actions action = new Actions(driver);
    action.keyDown(Keys.CONTROL).click(option1).click(option2).build().p erform();
    

    Above code will Select Maruti and Honda from a list. Here first we have put all the options which user wants to select into WebElement object and then used Actions Class to press down CTRL key and perform clicks on both options.

    Example :Print and select all the options for the selected Multiple selection list.

    import java.util.List;
    import java.util.concurrent.TimeUnit;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver; 
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver; 
    import org.openqa.selenium.support.ui.Select;
    
    public class MultiSelectCommands {
    
    public static void main(String[] args) throws InterruptedException {
    // Create a new instance of the FireFox driver WebDriver driver = new FirefoxDriver();
    
    // Put an Implicit wait
    driver.manage().timeouts().implicitlyWait(10,
    TimeUnit.SECONDS);
    
    // Launch the URL driver.get("http://toolsqa.wpengine.com/automation-
    practice-form");
    
    // Step 3: Select 'Selenium Commands' Multiple select box ( Use Name locator to identify the element )
    Select oSelect = new Select(driver.findElement(By.name("selenium_commands")));
    
    // Step 4: Select option 'Browser Commands' and then deselect it (Use selectByIndex and deselectByIndex)
    oSelect.selectByIndex(0); 
    Thread.sleep(2000); 
    oSelect.deselectByIndex(0);
    
    // Step 5: Select option 'Navigation Commands'	and then deselect it (Use selectByVisibleText and deselectByVisibleText)
    oSelect.selectByVisibleText("Navigation Commands"); 
    Thread.sleep(2000); 
    oSelect.deselectByVisibleText("Navigation Commands");
    
    // Step 6: Print and select all the options for the selected Multiple selection list.
    List<WebElement> oSize = oSelect.getOptions(); 
    int iListSize = oSize.size();
    
    // Setting up the loop to print all the options for(int i =0; 
    i < iListSize ; i++){
    // Storing the value of the option String sValue =
    oSelect.getOptions().get(i).getText();
    
    // Printing the stored value System.out.println(sValue);
    
    // Selecting all the elements one by one oSelect.selectByIndex(i); 
    Thread.sleep(2000);
    }
    
    // Step 7: Deselect all oSelect.deselectAll();
    
    // Kill the browser driver.close();
    }
    }	
    
    Select and Deselect Operations By Index, Value and Visible Text

    SelectByVisibleText: This method is used to choose or select an option given under any dropdowns and multiple selection boxes. It takes a parameter of String which is one of the Value of Select element and it returns nothing.

    Syntax:

    oSelect.selectByVisibleText(“text”);

    Example: To select the value 2010.

    Select oSelect=newSelect(driver.findElement(By.id("yy_date_8"))); 
    oSelect.selectByVisibleText("2010");
    

    Example: Any of the below html code can be taken as example.

    Webdriver example code to select the value by visible text.

    public class selectExamples {
    WebDriver driver; 
    @Test
    public void selectSamples()
    {
    driver = new FirefoxDriver(); 
    driver.get("C:\\Users\\dropdown-select.html");
    WebElement element=driver.findElement(By.name("Mobiles"));
    Select se=new Select(element); 
    se.selectByVisibleText("HTC");
    }
    }
    

    SelectByIndex: It is same as selectByVisibleText but the only difference is that in this method we provide the index number of the option rather the option text. It takes a parameter of int which is the index value of Select element and it returns nothing.

    Syntax:

    oSelect.selectByIndex(int);

    Example: To select the value 2010 using index.

    Select oSelect=newSelect(driver.findElement(By.id("yy_date_8"))); 
    oSelect.selectByIndex(4);
    

    Index starts from Zero, so the fifth position value will be at index 4.

    Example

    <html>
    <head>
    <title>Select Example by Index value</title>
    </head>
    <body>
    <select name="Mobiles"><option value="0" selected> Please select</option>
    <option value="1">iPhone</option>
    <option value="2">Nokia</option>
    <option value="3">Samsung</option>
    <option value="4">HTC</option>
    <option value="5">BlackBerry</option>
    </select>
    </body>
    </html>
    

    Example: Webdriver code for Selecting a Value using select.selectByValue(Value);

    public class selectByIndexExample { 
    WebDriver driver;
    @Test
    public void selectSamples()
    {
    driver = new FirefoxDriver(); 
    driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-
    samples\\Final Code\\chapter-07\\dropdown-select.html");
    WebElement element=driver.findElement(By.name("Mobiles"));
    Select se=new Select(element); se.selectByIndex(1);
    
    }
    }
    

    deselectByIndex: Deselect the option at the given index.

    Syntax:

    oSelect.deselectByIndex;

    selectByValue: This methodtakes the value of the option rather the option text or index. It takes a parameter of String which is on of the value of Select element and it returns nothing.

    Synatx:

    oSelect.selectByValue(“text”);

    Example: To select the value 2014

    Select oSelect=newSelect(driver.findElement(By.id("yy_date_8"))); 
    oSelect.selectByValue("2014");
    

    Example:

    <html>
    <head>
    <title>Select Example by Value</title>
    </head>
    <body>
    <p>Which mobile device do you like most?</p>
    <select name="Mobiles"><option selectd> Please select</option>
    <option value="iphone">iPhone</option>
    <option value="nokia">Nokia</option>
    <option value="samsung">Samsung</option>
    <option value="htc">HTC</option>
    <option value="blackberry">BlackBerry</option>
    </select>
    </body>
     
    </html>
    
    

    Webdriver code for Selecting a Value using select.selectByValue(Value);

    public class selectExamples { 
    WebDriver driver;
    @Test
    public void selectSamples()
    {
    driver = new FirefoxDriver();
    driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-
    samples\\Final Code\\chapter-07\\dropdown-select.html");
    WebElement element=driver.findElement(By.name("Mobiles"));
    Select se=new Select(element); se.selectByValue("nokia");
    
    }
    }
    

    deselectByValue: Deselect all options that have a value matching the argument.

    Synatx:

    oSelect.deselectByValue;

    deselectByVisibleText: Deselect all options that display text matching the argument.

    Synatx:

    oSelect.deselectByVisibleText

    deselectAll

    Syntax:

    select.deselectAll();

    Example: To clear all selected entries. This works only when the SELECT supports multiple selections. It throws NotImplemented eError if the “SELECT” does not support multiple selections. In select it mandatory to have an attribute multiple=”multiple”

    <html>
    <head>
    <title>Multi select Drop Down List Box</title>
    </head>
    <body>
    <p>What all devices do you listen to music on?</p>
    <select name="Mobdevices" multiple="multiple"><option value="0" selectd> Please select</option>
    <option value="1">iPhone</option>
    <option value="2">Nokia</option>
    <option value="3">Samsung</option>
    <option value="4">HTC</option>
    <option value="5">BlackBerry</option>
    </select>
    </body>
    </html>
    Webdriver code to show all the above deselect methods. public class selectExamples {
    WebDriver driver; 
    @Test
    public void selectSamples() throws InterruptedException
    {
    driver = new FirefoxDriver(); 
    driver.get("C:\\Users\\DEV\\Desktop\\html-and-css-code-
    samples\\Final Code\\chapter-07\\dropdown-select.html");
    WebElement element=driver.findElement(By.name("Mobdevices"));
    Select se=new Select(element);
    //Here we will take multi select dropdown to show you the
    difference
    
    se.selectByVisibleText("HTC"); 
    se.selectByValue("nokia");
    
    //From the above two commands, in the dropdown two values will be selected.
    //Now we will try to deselect any of the One
    //Im using thread to see the difference when selecting and selecting
    Thread.sleep(3000); 
    se.deselectByValue("nokia");
    
    //You can deselect the value by specifying the index, value and VisibleText
    
    
    //It will work if you the index is already selected se.deselectByIndex(1);
    
    mode
     
    //It will deselect if the visible text HTC is in selected se.deselectByVisibleText("HTC");
     
    //It will de-select all the values which are selected se.deselectAll();
    
    }
    }
    
    Summary
    • Web tables are a group of elements that are logically stored in a row and column format
    • Selenium WebDriver provides method getText() which can be used to read the innertext of any web element
    • Select is a class which is provided by Selenium to perform multiple operations on DropDown object and Multiple Select object
    • A drop-down list is a graphical control element, similar to a list box which allows the user to choose one value from a list

    Copyright 1999- Ducat Creative, All rights reserved.