Advance Selenium

How to handle calendar in Selenium Webdriver and web table

In my recent projects, I have handled a web table and calendar multiple times and in this article, I will show you how you can handle the calendar in Selenium Webdriver using the table approach.

I will use JQuery Date picker for example but you can take any example because the approach will remain the same. I will be using findElements methods to find all the dates and then will get the text and will click on the respective date.

The below image is an example of a Date picker which is a JQuery widget

JQuery Calendar

I have uploaded video handle calendar in Selenium Webdriver

 

 

 

 

 

Approach to handle calendar

Step 1- Click on calendar

Step 2- Get all td of tables using findElements method

Step 3- using for loop get the text of all elements

Step 4- using if else condition we will check the specific date

Step 5- If the date is matched then click and break the loop.

 

Program to handle calendar in Selenium Webdriver

package Blog;

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 CalendarHandling {

	public static void main(String[] args) 
	{
		// Set the driver path
		System.setProperty("webdriver.firefox.marionette","G:\\Selenium\\Firefox driver\\geckodriver.exe");
		
                // start firefox
		WebDriver driver=new FirefoxDriver();

                // start application
		driver.get("http://seleniumpractise.blogspot.com/2016/08/how-to-handle-calendar-in-selenium.html");
		
                // click on date picker so that we can get the calendar in view 
		driver.findElement(By.id("datepicker")).click();
			
                // this will find all matching nodes in calendar		
		List<WebElement> allDates=driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//td"));
		
                // now we will iterate all values and will capture the text. We will select when date is 28
		for(WebElement ele:allDates)
		{
			
			String date=ele.getText();
			
                        // once date is 28 then click and break
			if(date.equalsIgnoreCase("28"))
			{
				ele.click();
				break;
			}
			
		}
		
		
	}

}

 

There can be different approaches as well to handle calendar controls.

Approach 2- You can find the dates using XPath or CSSSelector and click on the dates directly.

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 CalendarHandling {

public static void main(String[] args)
{
// Set the driver path
System.setProperty("webdriver.firefox.marionette","G:\\Selenium\\Firefox driver\\geckodriver.exe");

// start firefox
WebDriver driver=new FirefoxDriver();

// start application
driver.get("http://seleniumpractise.blogspot.com/2016/08/how-to-handle-calendar-in-selenium.html");

// click on date picker so that we can get the calendar in view
driver.findElement(By.id("datepicker")).click();

// this will find all matching nodes in calendar
List<WebElement> allDates=driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//td"));

// Click on date 28 or any other date of your choice
driver.findElement(By.xpath("//a[text()='28']")).click();

}

}

Approach 3- You can also use JavaScriptExecutor which can set the date value directly in the date field. 

Hope you have enjoyed the article 🙂 Keep sharing and keep in touch.

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

45 thoughts on “How to handle calendar in Selenium Webdriver and web table

  1. RANJAN V says:

    Nice Tutorial)))

  2. Can you please post any blog for Dynamic Xpath especially for Calendar Controls ?

    1. Hi Himanshu,

      A blog post for the same is already under the pipeline. Please stay tuned..:)

  3. Ujjal Goswami says:

    Hi Mukesh,
    By using this approach,how can I click on a date which is 2 months later
    Please help.

    1. Hi Ujjal,

      In your scenario, you have to create xpath in such a way which should differ for both calendars

  4. Ranjeet says:

    hi mukesh ,i want to display all dates avail. on calender

    1. Hi Ranjeet,

      Create your xpath in such a way so that it should point to all dates in calendar. Each calendar has its own DOM structure.

  5. nayan kumar says:

    Hi how can i check if login credential from excel sheet is looged in application or not ,in excel sheet suppose we have n no of userid and password.

    1. Hi Navya,

      Here as soon as login happens, you can verify either page title or any other text/link on webpage which comes after successful login.

  6. Anvesh says:

    Hi Mukesh, i am a plain fresher to selenium with Java knowledge.. i am learning selenium by using your blog and videos..
    i am trying to automate gmail registration, here in selecting birthday(Month), i know how to select a particular month.. but, my requirement is to display the names of all months on consol.. can you please help me how can i implement the same… thanks in advance.

    1. Hi Anvesh,

      In order to display all the month, first click on Month control then only all months will get visible. Now iterating through those div will give you months name. And this is not standard select control so here select won’t works.

  7. Aarti says:

    Hi,

    I have a case in which I have to always pick tomorrow’s date from the calendar, I have the calendar icon and can easily select the current date by the script. How to automate this case using selenium. I am using java with selenium for automation.

      1. Neetu says:

        Hi Sir

        How can I select current date from calender

        1. Hi Neetu,

          You can use Date class and SimpleDateFormat class to capture dates in different formats. In the below post, I have explained how to get date time in the different formats. Check out the program 3 where I have captured only current date, which you can pass in your automated test.I hope it is clear now
          https://vistasadprojects.com/mukeshotwani-blogs-v2/how-to-get-current-system-date-and-time-in-java-selenium/

    1. Aarti
      This can help

      1) Get today’s date by using Date function in java
      2) Add 1 day to today’s date using Calendar function in java
      3) Once you have the date use selenium sendkeys into the textbox to select (today+1) date

      below is the code

      SimpleDateFormat df = new SimpleDateFormat(“MM/DD/YYYY”);
      Date dt = new Date();

      Calendar cl = Calendar.getInstance();
      cl.setTime(dt);;
      cl.add(Calendar.DAY_OF_YEAR, 1);
      dt=cl.getTime();

      String str = df.format(dt);

      System.out.println(“the date today is ” + str);
      drv.get(“http://seleniumpractise.blogspot.in/2016/08/how-to-handle-calendar-in-selenium.html”);
      WebElement el = drv.findElement(By.xpath(“//*[@id=’datepicker’]”));
      el.sendKeys(str);

      1. Hi Gaurav,

        Good…Thanks for putting solution.

        1. rupa says:

          what if the txtbox is disable so i can’t do send keys

          1. Hi Rupa,

            Selenium also perceives like we do via manual testing. Sendkeys in your context will not work but using javascript executor, you can play with some attributes which may enable your text box but it solely depends UI control

  8. Piyush says:

    Hi, Please can you tell me how to handle calendar of kendo as there is no table present.

    1. Hi Piyush,

      You will find table tag in Kendo UI as well.

  9. Sid says:

    List is throwing an error.
    org.openqa.selenium.remote.RemoteWebElement cannot be cast to java.util.List

    1. Hi sid it seems you have imported wrong package.

  10. santhosh says:

    ya really this is very helpful to us
    thanks for your postings mukesh

    1. Welcome santhosh 🙂

  11. Colleen says:

    This was really helpful. Thanks for posting.

    1. Most welcome Colleen, Keep visiting.

  12. Vnisha Sharma says:

    All concepts explained so well with clarity.
    Really helpful.

    Thank you

  13. solai says:

    Hi mukesh,

    I am not able open firefox browser using selenium code… it throws error.. what might be the proble??.. am using selenium 2.53.. initially it was working fine…

  14. laksha says:

    Hi Mukesh

    Pls help me to solve error in the below code in HANDLE CALENDAR CONCEPT

    in the below code it is not clicking and displaying date sep 30 in the returning date text box

    driver.manage().window().maximize();

    driver.get(“https://www.expedia.com/”);

    driver.findElement(By.id(“package-departing”)).click();
    Thread.sleep(3000l);
    List dates=driver.findElements(By.xpath(“//div[@class=’datepicker-cal’]”));

    for(WebElement ele:dates){
    String alldates=ele.getText();
    if(alldates.equalsIgnoreCase(“30”)){
    ele.click();
    break;
    }

    }

    1. Hi Laksha,

      Use below xpath .//*[@id=’hotel-checkin-wrapper’]/div/div/div[2]//td//button for all data and make below change

      old code
      String alldates=ele.getText();

      New code
      String alldates=ele.getAttribute(“innerHTML”);

  15. Sukanya says:

    Hi Vishal,
    Thanks for sharing. It surely helps. I was trying to automate a calendar control on “http://www.makemytrip.com”. The code snippet is as follows:
    List allDates = dr1.findElements(By.xpath(“//a[@class=’ui-state-default’]”));

    for (WebElement ele:allDates)
    {

    String current_date = ele.getText();
    System.out.println(current_date);
    if (current_date.equalsIgnoreCase(“16”))
    {
    ele.click();
    }
    }

    I am receiving “Element is no longer attached to the DOM ” at the “ele.click()” step. I am using SafariDriver for automation. Can you please advice.

    Thanks,
    Sukanya

    1. Hi Sukanya,

      Is the same code working with Chrome and Firefox as well?

  16. Madhur says:

    What if I wanted to select a specific date with a specific month and year?
    Will the month and year be handled as separate dropdown lists?

  17. Manohar says:

    hello Mukesh Otwani,
    Thank you for the tutorial(Handling Ca lender),But i question is You have written code for Date only.
    Can you explain code for Date-Month-Year(Ex-08-August-2017)

    1. Hi Manohar,

      You can apply the same logic for month and year as well.

  18. Jaswanth Majety says:

    Hello Mukesh Otwani, just thought to say thank you for the tutorial.
    This helped me great.

    1. Hey Jaswanth,

      Most welcome 🙂 Let me know if any help from my end

  19. vishal Garg says:

    Hi Mukesh,
    Hope you are doing good..

    I have one query just wanted to know which mozilla firefox version will be supported by webdriver version 2.47.0?

    I have Mozilla Version 45.0.0 it is not supported by webdriver 2.47.0. Please let me know if i have to go for lower version on Mozilla.

    Thanks &Regards
    Vishal Garg

    1. Hi Vishal,

      I am doing good and Thank you for wishes 🙂

      Selenium 3 is launched so kindly use below post

      https://vistasadprojects.com/mukeshotwani-blogs-v2/use-firefox-selenium-using-geckodriver-selenium-3/

      Note

      First Java 8 has to be installed
      Download Selenium3 and configure the same.

      1. Archana Patwari says:

        Hi Mukesh,
        I am handling a jquery pop up through alert.accept(), and while executig the script I get the following error. The jquery pop up is displayed but yes option is not selected on the jquery pop up:

        org.openqa.selenium.UnhandledAlertException: Unexpected modal dialog (text: Are you sure you want to deactivate?): Are you sure you want to deactivate?

        Could you please provide your inputs? How can we resolve this?

        1. Hi Archana,

          May be alert class is not able to identify JQuery pop up. It is better, if you proceed with directly click on OK button.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.