How to Handle Dynamic Web Table In Java Selenium Example Program?

Handle Dynamic Web Table: Nowadays, if you take a look at the web application, you can get various types of calendars they are using in their application, which are most similar to the HTML table. So we are going to take a look at some of these calendar applications and also going to learn about different calendars using selenium webdriver.

How to Handle Dynamic Web Table Calendar Using Selenium WebDriver?

Most of the application, we can see that when we click on date picker than a calendar widget open and from that calendar widget, we need to select the date as per our requirement.

Paytm.com calendar
https://jqueryui.com/datepicker/
https://jqueryui.com/resources/demos/ datepicker/dropdown-month-year.html
https://www.air.irctc.co.in/

You can see that as new technologies are coming to existence, everyone want to give a better look and introduce a new feature to their application, so for that, they are trying to implement various types and format of the calendar.

But as a tester, our job is to test such types of the calendar and need to certify that, so its a very challenging job to deal with such a calendar. As the format is changed and different from one calendar to another, we can not write a reusable method to handle all types of schedules.

In this post, we are taking the calendar example of India’s one of the most used platforms paytm. So we will discuss in detail how to handle such type of calendar application.

Understanding Calendar HTML:

As we share the above screenshot, you can see various types of calendars, but in all calendar applications, the common point is that all are built with a table format, which is consists of tables, rows, and columns. Out of that, a week represents a row that is to tag, and each date will be represented by td.

Implemented Logic:

Simple Format:

package com.selenium.advancedprograms;
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;
public class DynamicWebTable
{
   public static void main(String[] args) throws InterruptedException
   {
      WebDriver driver=new FirefoxDriver();
      driver.manage().window().maximize();
      driver.get("http://www.redbus.in/");
      driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
      driver.findElement(By.xpath(".//*[@id='search']/div/div[3]/span")).click();
      Thread.sleep(5000);
      List<WebElement> li=driver.findElements(By.xpath(".//*[@id='rb-calendar_onward_cal']/table/tbody/tr/td"));
      int size1=li.size();
      for(int i=0;i<size1;i++)
      {
         String date=li.get(i).getText();
         System.out.println(date);
         if(date.equals("21"))
         {
            li.get(i).click();
         }
      }
      driver.close();
   }
}

If you want to Make more customize, then you can check the below program:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class HandlingMMTCalendar 
{
   public static void selectDate(WebElement calendar, String year, String monthName, String day, WebDriver driver) throws ParseException
   {
      //Clicking on calendar to open calendar widget
      calendar.click();

      // Retrieving current year value
      String currentYear= driver.findElement(By.xpath("//div[@class='ui-datepicker-title']/span[@class='ui-datepicker-year']")).getText();

      // Click on Next arrow till we get desired year
      if(!currentYear.equals(year))
      {
         do{
            driver.findElement(By.xpath("(//span[text()='Next'])[1]")).click();
         }while(!driver.findElement(By.xpath("//div[@class='ui-datepicker-title']/span[@class='ui-datepicker-year']")).getText().equals(year));

      }

      // Select desired month after selecting desired year
      String currentMonth= driver.findElement(By.xpath("(//div[@class='ui-datepicker-title']/span[@class='ui-datepicker-month'])[1]")).getText();
      if(!currentMonth.equalsIgnoreCase(monthName))
      {
         do{
            driver.findElement(By.xpath("(//span[text()='Next'])[1]")).click();
         }
         while(!driver.findElement(By.xpath("(//div[@class='ui-datepicker-title']/span[@class='ui-datepicker-month'])[1]")).getText().trim().equalsIgnoreCase(monthName));

      }
      
      //get java month number for desired month
      int javaMonthInt= HandlingMMTCalendar.getMonthJavaInt(monthName);

      // Find dates of desired month only
      List<WebElement> allDateOfDesiredMonth= driver.findElements(By.xpath("//div[@class='ui-datepicker-group ui-datepicker-group-first']//table/tbody[1]//td[(@class=' ' or @class=' ui-datepicker-week-end ' ) and @data-month='"+javaMonthInt+"']"));
      for(WebElement d:allDateOfDesiredMonth )
      {
         if(d.getText().trim().equals(day))
         {
            d.click();
            break;
         }
      }

   }

   // Code to get java month number
   public static int getMonthJavaInt(String monthName) throws ParseException
   {

      Date date = new SimpleDateFormat("MMMM").parse(monthName);
      Calendar cal = Calendar.getInstance();
      cal.setTime(date);
      return cal.get(Calendar.MONTH);
   }

   public static void main(String[] args) throws ParseException 
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver= new ChromeDriver();
      driver.manage().window().maximize();
      driver.get("https://www.makemytrip.com/");

      // Locating departure date calendar
      WebElement departCal= driver.findElement(By.id("hp-widget__depart"));
      HandlingMMTCalendar.selectDate(departCal, "2017", "September", "22", driver);
   }
}

How to Calendar Having Month & Year Drop Down?

Above we have seen how to handle one type of calendar, and in this post, we are going to automate another type of calendar having month and year as a dropdown. You can see such example link here.

Here the scenarios:

  • The user first needs to click on the textbox.
  • After that, the calendar widget will open, and from that, we need to select the month and year

Let us see what logic should we need to follow to select a date:

  • As we are going to deal with the drop-down, so you need to aware of how to handle dropdown using selenium. If you do not know, then you can check our previous article, where we have written how to handle dropdown using selenium in detail.
  • Select the desired month from the drop-down.
  • Select the year from the drop-down.
  • Finally, select the day from the calendar widget.

Program:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
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 HandlingDropdownMonthYear 
{

   public static void selectDate(WebElement calendar, String year, String monthName, String day, WebDriver driver) throws ParseException, InterruptedException
   {
      //Clicking on calendar to open calendar widget
      calendar.click();

      // Select year first
      // Since drop down has been created using SELECT tag, We can use Select class.

      WebElement yearDropDown= driver.findElement(By.xpath("//select[@class='ui-datepicker-year']"));
      Select selectYear= new Select(yearDropDown);
      selectYear.selectByVisibleText(year);

      Thread.sleep(2000);

      // Select Month
      WebElement monthDropDown= driver.findElement(By.xpath("//select[@class='ui-datepicker-month']"));
      Select selectMonth= new Select(monthDropDown);
      selectMonth.selectByVisibleText(monthName);

      // Select date
      WebElement date= driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']//tbody//tr/td/a[text()='"+day+"']"));
      date.click();

      // Printing selected date
      String selectedDate= calendar.getAttribute("value");
      System.out.println("Selected Date: "+selectedDate);

      driver.quit();
   }

   // Code to get java month number
   public static int getMonthJavaInt(String monthName) throws ParseException
   {
      Date date = new SimpleDateFormat("MMMM").parse(monthName);
      Calendar cal = Calendar.getInstance();
      cal.setTime(date);
      return cal.get(Calendar.MONTH);
   }

   public static void main(String[] args) throws ParseException, InterruptedException 
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver= new ChromeDriver();
      driver.manage().window().maximize();
      driver.get("https://jqueryui.com/resources/demos/datepicker/dropdown-month-year.html");

      // Locating departure date calendar
      WebElement departCal= driver.findElement(By.id("datepicker"));
      HandlingDropdownMonthYear.selectDate(departCal, "2018", "Sep", "23", driver);

   }
}

How to Handle the same Scenario with the Help of JavaScript?

As you can saw that to handle the above scenario, we need to write lengthy code. But we can handle the same scenario with the help of JavaScript.

JavaScript provides so many methods, but for this scenario, we can use the setAttribute() method. By using this method, we can set an attribute to a specified element. If the attribute already exists on an element, then the value is updated, and if the attribute is not there, then the new attribute is added with the specified name and value.

Syntax: setAttribute(“attributeName”,”attributeValue”)

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingAnyCalendarUsingJavaScript 
{
   public static void setDateUsingJavaScriptInCalendar(WebDriver driver, String value, WebElement calLocator)
   {
      JavascriptExecutor jse= (JavascriptExecutor)driver;
      String script= "arguments[0].setAttribute('value','"+value+"');";
      jse.executeScript(script, calLocator);
   }
   public static void main(String[] args) 
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver= new ChromeDriver();
      driver.manage().window().maximize();
      driver.get("https://jqueryui.com/resources/demos/datepicker/dropdown-month-year.html");

      // Locating departure date calendar
      WebElement departCal= driver.findElement(By.id("datepicker"));
      HandlingAnyCalendarUsingJavaScript.setDateUsingJavaScriptInCalendar(driver,"10/09/2017",departCal);
   }
}

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment