How can I select date from a datepicker div using Selenium Webdriver?

We can select data from a datepicker using Selenium webdriver. A datepicker in a calendar can be designed in numerous ways on the web UI. Based on the UI, we have to design our test.

A calendar may have a dropdown for selection of day, month or year. It may also contain forward and backward navigation to move up and down in the dates or any other design. The below example shows a calendar having a datepicker. Let us make an attempt to select the date 03/02/2021(2nd March, 2021) date from the below calendar −

In the above html code, we can see the calendar within a table tag identified by the <table> and its dates are represented by the rows and columns having the <tr> and the <td> tags respectively(tr being the parent of td). To select a date, we need to identify all the elements having <td> tag using the findElements method.

This method returns a list of matching elements. We have to traverse through this list and check a specific date with the help of the getText method. Once we encounter the required date, we shall select it and break out from 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 DtPicker{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      //switch to frame
      WebElement f = driver .findElement(By.xpath("//iframe[@class='demo-frame']"));
      //identify element within frame
      WebElement l = driver.findElement("datepicker"));;
      //identify all td elements in list
      List<WebElement> t =driver.findElements(By.xpath("//table/tbody/tr/td"));
      //list traversal
      for (int k = 0; k<t.size(); k++) {
         //check date
         String dt = t.get(k).getText();
         if (dt.equals("2")) {
      //obtain selected date
      String v = l.getAttribute("value");
      System.out.print("Date selected by date picker: "+ v);
      //close browser


Updated on: 03-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started