Friday, 10 October 2014

Selecting a date from Datepicker using Selenium WebDriver

Calendars look pretty and of course they are fancy too.So now a days most of the websites are using advancedjQuery Datepickers instead of displaying individual dropdowns for month,day,year. :P
If we look at the Datepicker, it is just a like a table with set of rows and columns.To select a date ,we just have to navigate to the cell where our desired date is present.

Step 1:  Here I am taking Sample Website "http://www.cleartrip.com/"
step 2:  Here we can able to select date whatever we want( This is pure dynamic)
step 3:  Here I am Implementing all my logic in 'genericDatePicker()' Method. This method i am   passing date(date format should be dd/mm/yyyy).
step 4: Here First I am Clicking Calendar field and then i am getting Month/Year.
Step 5: I have written Enum method(I am assigning Number to every Month)
Step 6: After that I am calculating total months.
Step 7: Finally I am Clicking the Date From DatePicker..

Here is a sample code on how to pick a 26/10/2016..

  1. package com.utility;

    import java.util.List;

    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver; 
  2. public class RedBus {
      WebDriver driver;
    @Before
    public void setUp() throws Exception {
    driver = new FirefoxDriver();
    driver.get("http://www.cleartrip.com/");
    driver.manage().window().maximize();
    }

    @Test
    public  void datePicker(){
    genericDatePicker("26/09/2016");  //date format should be dd/mm/yy
    }

    public  void genericDatePicker(String inputDate){
    /* CLicking the Date Feild*/
    WebElement ele =driver.findElement(By.id("DepartDate"));  
    ele.click();
    /*Here we are getting Month and Year */
    String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
    String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
    System.out.println("Application month : "+month + " Year :"+year);
    int monthNum = getMonthNum(month);
    System.out.println("Enum Num : "+monthNum);
    String[] parts = inputDate.split("/");   // Here I am Spliting Our Input String Value
    //Here I am Implementing the Logic
    int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
    System.out.println("No OF Hits "+noOfHits);
    for(int i=0; i< noOfHits;i++){
    driver.findElement(By.className("nextMonth ")).click();
    }
    /* selecting the month div*/
    List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
    System.out.println(cals.size());
    /*iterating the "tr" list*/
    for( WebElement daterow : cals){
    /*getting the all "td" s*/
    List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
    /*iterating the "td" list*/
    for(WebElement date : datenums ){
    /* Checking The our input Date(if it match go inside and click*/
    if(date.getText().equalsIgnoreCase(parts[0])){
    date.click();
    break;
    }
    }
    }
    }

    // This method will return Month Number
    public  int getMonthNum(String month){
    for (Month mName : Month.values()) {
    if(mName.name().equalsIgnoreCase(month))
    return mName.value;
    }
    return -1;
    }

    // Here I am Creating Enum Method(I am assigning Number to every Month)
    public enum Month {
    January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
    private int value;

    private Month(int value) {
    this.value = value;
    }

    }

      @After
    public void tearDown() throws Exception {
    driver.quit();
    }


    }

4 comments:

  1. Really good work helped me a lot...
    I'm new to selenium and need some help at work in getting text from popup which appears only on mouse over.can u send your email Id at hallgames63@gmail.com...

    ReplyDelete
  2. Hi Brahma,

    Need ur Expert guidance, want to read data from data grin in specific date range like 2014 year data only , i tried this logic but it never work .

    import java.util.List;
    import java.util.concurrent.TimeUnit;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.openqa.selenium.By;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.Select;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;

    public class DateRange {

    WebDriver driver = new FirefoxDriver();
    protected static HSSFWorkbook wb = new HSSFWorkbook(); // or new XSSFWorkbook();
    protected static HSSFSheet sheet1 = wb.createSheet("IHSharedHeld");


    @BeforeTest
    public void setup() throws Exception {
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    driver.get("http://www.nasdaq.com/symbol");
    driver.findElement(By.id("stock-search-text")).clear();
    driver.findElement(By.id("stock-search-text")).sendKeys("AB");
    driver.findElement(By.id("stock-search-submit")).click();

    JavascriptExecutor jsedown = (JavascriptExecutor)driver;
    jsedown.executeScript("scroll(0, 250)");

    //Click on holdings link.
    driver.findElement(By.id("holdingslink")).click();
    System.out.println("Action should counduct once ");
    Thread.sleep(3000);
    }

    @AfterTest
    public void tearDown() throws Exception {
    driver.quit();
    }
    @Test
    public void print_data() throws Exception{

    //Get number of rows In table.
    int Row_count = driver.findElements(By.xpath(".//*[@id='quotes_content_left_pnlInsider']/table/tbody/tr")).size();
    System.out.println("Number Of Rows = "+Row_count);

    //Get number of columns In table.
    int Col_count = driver.findElements(By.xpath(".//*[@id='quotes_content_left_pnlInsider']/table/tbody/tr[1]/td")).size();
    System.out.println("Number Of Columns = "+Col_count);

    //divided xpath In three parts to pass Row_count and Col_count values.
    String first_part = ".//*[@id='quotes_content_left_pnlInsider']/table/tbody/tr[";
    String second_part = "]/td[";
    String third_part = "]";
    //String forth_part = ".//*[@id='quotes_content_left_pnlInsider']/table/tbody/tr[]/td[2]";
    String forth_part = "td[2]";
    //Used for loop for number of rows.
    for (int k=1; k<=Row_count; k++){

    //Used for loop for number of columns.
    for(int j=1; j<=3; j++){

    System.out.print(forth_part +" ");
    if(forth_part.matches("(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((2014)\\d\\d)")){

    String final_xpath1 = first_part+k+second_part+j+third_part;
    String Table_data1 = driver.findElement(By.xpath(final_xpath1)).getText();
    System.out.print(Table_data1 +" ");
    }
    else{
    System.out.println("No data Found ");
    }
    }
    }
    }
    }

    ReplyDelete
  3. public enum Month {
    why it is showing error in month

    ReplyDelete
  4. Hi prativa, What type of error your getting...

    ReplyDelete

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...