Tuesday 27 May 2014

Select Date Using Selenium Webdriver

How To Select Date From DatePicker Using Selenium WebDriver.......

A lot of application has datepicker which shows calenders upon clicking on it. The reason is to test, Does it shows calender after clicking on it and get the user selected date. So here currently working on Selenium WebDriver. I want to select values in date range from the drop down.. I want to know how can i select the values as Date, Month and year in the date picker drop down.

Following code will open the url in firefox once it come up, click on text box which shows calender and then naviage to February and select the defined date in the code below. It will show name of month in console window.  

Here we go.........

import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebElement;
import java.util.List;
import java.util.concurrent.TimeUnit;

 

public class demoDatePicker {

    public static void main(String[] args) {


               WebDriver driver = new FirefoxDriver();

        driver.get("http://jqueryui.com/datepicker/");
        driver.manage().window().maximize();

        WebElement ele = driver.findElement(By.className("demo-frame"));
        driver.switchTo().frame(ele);

        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        // Click on text box so that date picked will come
        driver.findElement(By.id("datepicker")).click();
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

        for (int i = 0; i < 12; i++) {
            // Get month string
            String month = driver.findElement(By.className("ui-datepicker-month")).getText();
            if(month.equalsIgnoreCase("February"))
                break;
            driver.findElement(By.xpath("/html/body/div/div/a[2]/span")).click();
            System.out.println(month);
        }

        // Date picker is a table so that navigate to each cell, If particular
        // cell matches value 20 then select it

        WebElement dateWidget = driver.findElement(By.className("ui-datepicker-calendar"));

        List<WebElement> rows = dateWidget.findElements(By.tagName("tr"));
        List<WebElement> columns = dateWidget.findElements(By.tagName("td"));

        // select 20th date
        for (WebElement row : rows) {
            for (WebElement col : columns) {
                if (col.getText().equals("20")) {
                    col.click();
                    break;
                }
            }
        }
    }
}


No comments:

Post a Comment

Select Language