Handling HTML Form Elements.

Almost in every web application, we inputs some values, Selects Options/Checkbox clicks on links/buttons etc through html elements and submit the page and save/retrieve values.

Today we will see how to interact with all these HTML elements (Web Controls).
WebDriver treats all those elements as a same that is WebElement.

below is the list of web controls and their HTML Syntax.


NameHTML SyntaxControl
Hyper Link
<a href="#">Link</a>
My Simple Link
Text Box
<input type="text" value="Some Text"/>
Password
<input type="password" value="somepass"/>
Multiline Textbox
<textarea>Firstline
Secondline
</textarea>
Checkbox
<input name="check1" type="checkbox"/>checkbox 1
       <input name="check2" type="checkbox"/>checkbox 2
checkbox 1   checkbox 2
Radio Button
<input name="options" type="radio" value="Option1" />Option 1
<input name="options" type="radio" value="Option2" />Option 2
Option 1   Option 2
Input Button
<input type="button" value="Click Me" id="myInpButton" />
Button
<button id="myButton">Click Me</button>
Submit Button
<input type="Submit" id="mySubmit" />
Combo Box
   <select>
      <option>Value 1</option>
      <option>Value 2</option>
      <option>Value 3</option>
   </select>
Multi Select ListBox
<select multiple="multiple" size="5">
   <option>Value 1</option>
   <option>Value 2</option>
   <option>Value 3</option>
   <option>Value 4</option>
   <option>Value 5</option>
</select>


Click Elements :

Below elements are generally used for Click interaction, also many time we need to verify element is enabled / disabled
  • Hyper Link
  • Input Button
  • Button
  • Submit Button
to click on all above controls we can use click() Method
to check the element is enabled we use isEnabled() Method
Check the below code
  WebDriver driver = new FirefoxDriver();
  driver.get("http://seleniumbyneeds.blogspot.in/2015/01/handling-various-html-form-elements.html");
  // Click on Button
  driver.findElement(By.id("button")).click();
  // Verify input button enabled if yes click on it
  if(driver.findElement(By.id("inpButton")).isEnabled()){
    driver.findElement(By.id("inpButton")).click();
  }
  // Click on link by selecting by link text
  driver.findElement(By.linkText("My Simple Link")).click();




Text Elements

Below elements used to enter text/numbers/words
  • Text Box
  • Password
  • Multiline Textbox
to enter the text, We use .sendKeys() Method with desired text as argument to read text from Multi line TextBox we use .getText() Method but to read the text from the TextBox & Password element we should use .getAttribute("value")
to clear the text from elements we can use clear()
please check below code
  WebDriver driver = new FirefoxDriver();
  driver.get("http://seleniumbyneeds.blogspot.in/2015/01/handling-various-html-form-elements.html");
  // Enter the text in text box
  driver.findElement(By.id("tbox")).sendKeys("Hello there");
  // print the text from text tbox
  System.out.println(driver.findElement(By.id("tbox")).getAttribute("value"));
  // enter the text in multi line text box
  driver.findElement(By.id("tarea")).sendKeys("here comes line 1\nhere comes line 2");
  // print the text from multi line text tbox
  System.out.println(driver.findElement(By.id("tarea")).getText());
  // Clear the password field
  driver.findElement(By.id("pass")).clear();



Selection Elements

Here in this category we get multiple options to select from them, below is the list of selection elements
  • Checkbox
  • Radio Button
  • Combo Box
  • Multi Select ListBox
to check or un-check the CheckBox we use click() Method.
to verify the CheckBox is checked we use .isSelected() Method

to select & verify selected Radio buttons, same methods are used

to select the specific option from Combo Box & Multi Select ListBox Selenium WebDriver provides Special class org.openqa.selenium.support.ui.Select
Below is code snippet which use to select single or multiple options.
WebDriver driver = new FirefoxDriver();
  driver.get("http://seleniumbyneeds.blogspot.in/2015/01/handling-various-html-form-elements.html");
  //Check the checkbox
  driver.findElement(By.name("check1")).click();
  //Check the checkbox 2 if it is not checked
  if(driver.findElement(By.name("check2")).isSelected()){
     driver.findElement(By.name("check2")).click();
  }
  // select the option Value 2 from combo box
  // 1. Convert WebElement to Select
  // 2. Select the desired option
  Select comboBox = new Select(driver.findElement(By.id("myCombo")));
  comboBox.selectByVisibleText("Value 2");
  //
  // Multi select from the list
  //
  Select listBox = new Select(driver.findElement(By.id("myCombo")));
  listBox.selectByVisibleText("Value 1");
  listBox.selectByVisibleText("Value 2");
  //
  // deselect the specific item
  //
  listBox.deselectByValue("Value 1");
  //
  // De-select all the items from the list 
  //
  listBox.deselectAll();

Select class also provide other useful methods to interact with List and combo
getFirstSelectedOption() returns the first selected element from the list
getAllSelectedOptions() returns List of WebElement which are selected

Note: Other then Visible text there are also methods available for index & value attribute


Keep Exploring... & Keep Automating......

Selecting Date on JQuery Datepicker

Hello Friends,

In this post we will see how to select specific date in JQuery Datepicker.

Its very easy to enter date as text by .sendKeys() method, but mostly when application uses JQuery Datepicker, it disables typing on the text-box. the text-box sets to read only.

While automating such screens we need to write logic which can interact with Datepicker and selects desired date.

Consider below example of Datepicker.


Html code for above example is


To automate this, we first break apart a problem.
  1. Decide which date we want to set 
  2. Read the current date from datepicker 
  3. Calculate difference between both dates in Months(difference will positive in case of set date is in future respective to current date & will negative when set date is in past respective to current date of datepicker) 
  4. Set loop depends on month difference and navigate the datepicker to specific month 
  5. Select the Day. 

Lets implement the above logic.
Note: we have used Joda Date Time Library for calculate date and time difference
 
 SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
  SimpleDateFormat calDateFormat = new SimpleDateFormat("MMMM yyyy");
  Date setDate=myDateFormat.parse("15/08/2014");
  WebDriver driver = new FirefoxDriver();
  driver.get("http://seleniumbyneeds.blogspot.in/2015/01/selecting-date-on-jquery-datepicker.html");
  // Switch to frame where the Menu Example is loaded
  driver.switchTo().frame(driver.findElement(By.id("myFiddler"))).switchTo().frame(0);
  driver.findElement(By.id("datepicker")).click();
  Date curDate = calDateFormat.parse(driver.findElement(By.className("ui-datepicker-title")).getText());
  // Joda org.joda.time.Months class to calculate difference
  // to do this converted Date to joda DatTime
  int monthDiff = Months.monthsBetween(new DateTime(curDate).withDayOfMonth(1), new DateTime(setDate).withDayOfMonth(1)).getMonths();
  boolean isFuture = true;
  // decided whether set date is in past or future
		if(monthDiff<0){
			isFuture = false;
			monthDiff*=-1;
		}
		// iterate through month difference
		for(int i=1;i<=monthDiff;i++){
			driver.findElement(By.className("ui-datepicker-" + (isFuture?"next":"prev"))).click();
		}
		// Click on Day of Month from table
		driver.findElement(By.xpath("//table[@class='ui-datepicker-calendar']//a[text()='" + (new DateTime(setDate).getDayOfMonth()) + "']")).click();



Hope this will help you.... you can directly use above code if your application is using JQuery Datepicker. Keep automating......

Handling Dates in Java

Date is one of the Important Variable type in Java, Generally we use following actions with Dates while Automating the application

1) Read and Write date in Different Format

When we read date from browser, it is String type Variable. which is not suitable for perform date like operation. so that we need to convert the string to Date We can convert the string to date using SimpleDateFormat Below is different patterns used

LetterDescriptionExamples
yYear2013
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60
Note: If ‘M’ is 3 or more, then the month is interpreted as text, else number
Example 1:

 SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
 String dateString = "07-Jun-2013";
  try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
 } 
  catch (ParseException e) {
  e.printStackTrace();
 }
Output:
Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013

in above case we have String dateString in format dd-MMM-yyyy, so to convert the String to Date in given format we have Created Object formatter of Class SimpleDateFormat.

This class provides various methods but for now out of that parse and format are important for us

  • parse Method takes String in argument and returns Date Object 
  • format Method takes Date in argument and returns formatted String
Example 2:

 
 SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
 SimpleDateFormat parser = new SimpleDateFormat("dd/MMM/yyyy");
 String dateString = "31-10-2013";
  try {
    Date date = formatter.parse(dateInString);
    System.out.println(parser.format(date));
 } 
  catch (ParseException e) {
  e.printStackTrace();
 }
Output:
31/Oct/2013

In Example 2, we are converting the format of the given Date String by using separate SimpleDateFormat for parsing and formatting.


2) Compare Dates


To compare dates we use Date.compareTo(), this is the classic method to compare dates in Java. the method returns the results as follows.
  • Return value is 0 if both dates are equal.
  • Return value is greater than 0 , if Date is after the date argument.
  • Return value is less than 0, if Date is before the date argument.
 
try{
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  Date date1 = sdf.parse("2009-12-31");
  Date date2 = sdf.parse("2010-01-31");
  System.out.println(sdf.format(date1));
  System.out.println(sdf.format(date2));
  if(date1.compareTo(date2)>0){
    System.out.println("Date1 is after Date2");
  }else if(date1.compareTo(date2)<0){
    System.out.println("Date1 is before Date2");
  }else if(date1.compareTo(date2)==0){
    System.out.println("Date1 is equal to Date2");
  }else{
    System.out.println("How to get here?");
  }
  }catch(ParseException ex){
 ex.printStackTrace();
}

3) Find Difference between two dates


The best way to get difference between two dates is to get difference in milliseconds and convert them in to required format(days, hours, min, seconds)
  • 1000 milliseconds = 1 second
  • 60 seconds = 1 minute
  • 60 minutes = 1 hour
  • 24 hours = 1 day
I have tried explained in below example.

String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
 
  //HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
 
Date d1 = null;
Date d2 = null;
 
try {
  d1 = format.parse(dateStart);
  d2 = format.parse(dateStop);
 
   //in milliseconds
  long diff = d2.getTime() - d1.getTime();
 
  long diffSeconds = diff / 1000 % 60;
  long diffMinutes = diff / (60 * 1000) % 60;
  long diffHours = diff / (60 * 60 * 1000) % 24;
  long diffDays = diff / (24 * 60 * 60 * 1000);
 
  System.out.print(diffDays + " days, ");
  System.out.print(diffHours + " hours, ");
  System.out.print(diffMinutes + " minutes, ");
  System.out.print(diffSeconds + " seconds.");
 
}
catch (Exception e)
{
  e.printStackTrace();
}

hope this will help you some where....

Keep Automating..

Using Actions Class to perform user actions


Hello Friends....

Today we will see how to handle series of events with Selenium WebDriver.

Now you will have question What is Series of events or actions and Where do I need while automating the application?

Have a look in below menu, having 2 Levels of sub menu. 
below is the source HTML of the page

<ul class="top">
    <li><a href="#">Menu1</a></li>
    <li><a href="#">Menu2 >></a>
        <ul class="sub">
            <li><a href="#">SubMenu1</a></li>
            <li> <a href="#">SubMenu2 >></a>

                <ul class="sub">
                    <li><a target="_blank" href="http://www.google.com">Link to Google</a>
                    </li>
                    <li><a href="http://facebook.com">Link to Facebook</a>

                    </li>
                </ul>
            </li>
            <li><a href="#">SubMenu3</a>

            </li>
        </ul>
    </li>
    <li><a href="#">Menu3</a>
    </li>
</ul>


I want to click on menu Menu2 >> SubMenu2 >> Link to Google

if we execute below code.

    /*** 
     *Initializing WebDriver to FirefoxDriver
    ***/
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumbyneeds.blogspot.in/2015/01/using-actions-to-hover-on-menu.html");
     
    // Switch to frame where the Menu Example is loaded
    driver.switchTo().frame(driver.findElement(By.id("myFiddler"))).switchTo().frame(0);
    
//Clicking in Link
driver.findElement(By.partialLinkText("Google")).click();


By executing above code we will get below error message. Because link to Google is not directly visible.

Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"partial link text","selector":"Google"} 

to get the link visible we need 2 actions
  • Hover on Menu2, which will display SubMenu2  
  • Hover on SubMenu2, which will expose or display Link to Google
  • and after that we click on link to Google
 to simulate all above actions we will need Actions, this class provides lot of user actions and gestures which simulates the user interactions and events.

see below code which uses Actions class to perform above mentioned actions to click on Google Link

  WebDriver driver = new FirefoxDriver();
  driver.get("http://seleniumbyneeds.blogspot.in/2015/01/using-actions-to-hover-on-menu.html");

// Switch to frame where the Menu Example is loaded
  driver.switchTo().frame(driver.findElement(By.id("myFiddler"))).switchTo().frame(0);
 
//initializing object from Class org.openqa.selenium.interactions.Actions
 Actions myActionBuilder = new Actions(driver);
//hover on Menu2
  myActionBuilder.moveToElement(driver.findElement(By.partialLinkText("Menu2"))).build().perform();
//hover on SubMenu2
  myActionBuilder.moveToElement(driver.findElement(By.partialLinkText("SubMenu2"))).build().perform();
//click on link
  myActionBuilder.moveToElement(driver.findElement(By.partialLinkText("Google"))).click().build().perform();



Here in this example we have used moveToElement action, which triggers the hover event on the given WebElement.


Now lets see drag and drop example in Actions


Have a look in below Example, in this we need to drag first block to second block

below is the html source of the example.
to perform drag and drop operation we will need below code.

  WebDriver driver = new FirefoxDriver();
  driver.get("http://seleniumbyneeds.blogspot.in/2015/01/using-actions-to-hover-on-menu.html");
  driver.switchTo().frame(driver.findElement(By.id("myDragFiddler"))).switchTo().frame(0);
  Actions myActionBuilder = new Actions(driver);
  myActionBuilder.dragAndDrop(driver.findElement(By.id("draggable")), driver.findElement(By.id("droppable"))).build().perform();

Like above both examples we can do lot of actions with Actions class, just play around and explore the things.


Keep Automating.....