Tuesday, December 30, 2014

Selecting a date from Datepicker using Selenium WebDriver

  driver.switchTo().frame(0); 
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
 //Click on textbox so that datepicker will come 
  driver.findElement(By.id("datepicker")).click(); 
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); 
  //Click on next so that we will be in next month 
  driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click(); 
   
  /*DatePicker is a table.So navigate to each cell  
   * If a particular cell matches value 13 then select it 
   */ 
  WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div")); 
  List rows=dateWidget.findElements(By.tagName("tr")); 
  List columns=dateWidget.findElements(By.tagName("td")); 
   
  for (WebElement cell: columns){ 
   //Select 13th Date  
   if (cell.getText().equals("13")){ 
   cell.findElement(By.linkText("13")).click(); 
   break; 
   } 
  }  
 
  (OR)
 
   WebElement dateWidget;
 List rows;
 List columns;
 List list = Arrays.asList("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
 // Expected Date, Month and Year
 int expMonth;
 int expYear;
 String expDate = null;
 // Calendar Month and Year
 String calMonth = null;
 String calYear = null;
 boolean dateNotFound;

 driver.switchTo().frame(0);
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
  //Click on textbox of Date so that datepicker will appear
  driver.findElement(By.id("datepicker")).click();
  dateNotFound = true;
  expMonth= 3;
  expYear = 2015;
  expDate = "12";
  while(dateNotFound)
  {
 
   calMonth = driver.findElement(By.className("ui-datepicker-month")).getText();
   calYear = driver.findElement(By.className("ui-datepicker-year")).getText();
   if(list.indexOf(calMonth)+1 == expMonth && (expYear == Integer.parseInt(calYear)))
   {
    selectDate(expDate);
    dateNotFound = false;
   }
   else if(list.indexOf(calMonth)+1 < expMonth && (expYear == Integer.parseInt(calYear)) || expYear > Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();
   }
   else if(list.indexOf(calMonth)+1 > expMonth && (expYear == Integer.parseInt(calYear)) || expYear < Integer.parseInt(calYear))
   {
    driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[1]/span")).click();
   }
  }
  Thread.sleep(3000);
 }

 public void selectDate(String date)
 {
 dateWidget = driver.findElement(By.id("ui-datepicker-div"));
 rows=dateWidget.findElements(By.tagName("tr"));
 columns=dateWidget.findElements(By.tagName("td"));

 for (WebElement cell: columns){
  //Selects Date
  if (cell.getText().equals(date)){
   cell.findElement(By.linkText(date)).click();
   break;
  }
 }
 }

 
Datepicker

No comments:

Post a Comment