Wednesday, 3 July 2013

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 advanced jQuery Datepickers instead of displaying individual dropdowns for month,day,year. :P

Datepicker

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.

Here is a sample code on how to pick a 13th date from the next month.
  1. import java.util.List;  
  2. import java.util.List;  
  3. import java.util.concurrent.TimeUnit;  
  4. import org.openqa.selenium.By;  
  5. import org.openqa.selenium.WebDriver;  
  6. import org.openqa.selenium.WebElement;  
  7. import org.openqa.selenium.firefox.FirefoxDriver;  
  8. import org.testng.annotations.BeforeTest;  
  9. import org.testng.annotations.Test;;  
  10.   
  11. public class DatePicker {  
  12.   
  13.  WebDriver driver;  
  14.    
  15.  @BeforeTest  
  16.  public void start(){  
  17.  System.setProperty("webdriver.firefox.bin""C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");    
  18.  driver = new FirefoxDriver();  
  19.  }  
  20.    
  21.  @Test  
  22.  public void Test(){  
  23.    
  24.   driver.get("http://jqueryui.com/datepicker/");  
  25.   driver.switchTo().frame(0);  
  26.   driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);  
  27.   //Click on textbox so that datepicker will come  
  28.   driver.findElement(By.id("datepicker")).click();  
  29.   driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);  
  30.   //Click on next so that we will be in next month  
  31.   driver.findElement(By.xpath(".//*[@id='ui-datepicker-div']/div/a[2]/span")).click();  
  32.     
  33.   /*DatePicker is a table.So navigate to each cell   
  34.    * If a particular cell matches value 13 then select it  
  35.    */  
  36.   WebElement dateWidget = driver.findElement(By.id("ui-datepicker-div"));  
  37.   List<webelement> rows=dateWidget.findElements(By.tagName("tr"));  
  38.   List<webelement> columns=dateWidget.findElements(By.tagName("td"));  
  39.     
  40.   for (WebElement cell: columns){  
  41.    //Select 13th Date   
  42.    if (cell.getText().equals("13")){  
  43.    cell.findElement(By.linkText("13")).click();  
  44.    break;  
  45.    }  
  46.   }   
  47.  }  
  48. }</webelement></webelement>  

1 comment:

Angular JS Protractor Installation process - Tutorial Part 1

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