How to automate Calendar using Selenium WebDriver for Testing?

SeleniumAutomation TestingTesting Tools

We can automate a calendar using Selenium webdriver. It may be a bit difficult to automate tests on a calendar since the selection of day, month, and year can be different in web UI from one calendar to another.

A calendar can be in the form of a dropdown selection or with backward and forward buttons to select up and down in dates or with any other features. Let us see an example of selection of the 03/02/2021(2nd March, 2021) date in the below calendar −

In the above example, the calendar is within a table. A table is represented by <table> tag and its rows are represented by the <tr> tag and columns by <td> tag.

To pick a date, we have to access all the elements within the td tag with the help of the findElements method.

The findElements method returns a list of elements. We shall iterate over this list(with a loop) and search a particular date. Once we get the expected date, we would click on it and then break out of the loop.


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import java.util.List;
public class CalendarDt{
   public static void main(String[] args) {
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      //identify and switch to frame
      WebElement r = driver.findElement(By.xpath("//iframe[@class='demo-frame']"));
      //identify element
      WebElement e = driver.findElement("datepicker"));;
      //identify elements with td tag in list
      List<WebElement> d =driver.findElements(By.xpath("//table/tbody/tr/td"));
      //iterate list
      for (int i = 0; i<d.size(); i++) {
         //check expected data
         String s = d.get(i).getText();
         if (s.equals("2")) {
      //get data selected
      String m = e.getAttribute("value");
      System.out.print("Date selected in calendar is: "+ m);
      //close browser


Published on 08-Apr-2021 11:07:51