Wednesday, 10 September 2014

Selenium User Interactions


As Selenium Webdriver is the most used tools among selenium tool set, it is important for us to understand how to use selenium to interact with web apps. In this module, let us understand how to interact with GUI objects using selenium webdriver.
We need to interact with the application using some basic actions or even some advanced user action by developing user defined function for which there are no predefined commands.
Following are the different kinds of actions against those GUI objects. Click on each one of the below actions to understand better.
  • Text Box Interaction
  • Radio Button Selection
  • Check Box Selection
  • Drop Down Item Selection
  • Synchronization
  • Drag & Drop
  • Keyboard actions
  • Mouse actions
  • Multi Select
  • Find all Links

Selenium Find all Links

Find all Links

Testers might be in a situation to grep all the links on website. We can easily do so by finding all elements with Tag Name "a" as we know that for any link reference in HTML we need to use "a" (anchor) tag.

Example

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class getalllinks
{
  public static void main(String[] args)
  {
 WebDriver driver = new FirefoxDriver();
 driver.navigate().to("http://www.calculator.net");
 java.util.List<WebElement> links = driver.findElements(By.tagName("a"));
 System.out.println("Number of Links in the Page is " + links.size());
 for (int i = 1; i<=links.size(); i=i+1)
 {
   System.out.println("Name of Link# " + i - + links.get(i).getText());
 }    
  }
}

Output

The Output of the script would be thrown to console as shown below. Though there are 65 links only partial output is shown below.
Selenium IDE 91

Selenium Multi Select Action

Multi Select Action

Sometimes we would be in a situation to select two or more items in a list box or text area. To understand the same, we would demostrate multiple selection from the list using 'http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx'.

Example

Let us say, we want to select 3 items from this list as shown below:
selenium_ide_187
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

public class webdriverdemo
{
  public static void main(String[] args) throws InterruptedException
  {
 WebDriver driver = new FirefoxDriver();

 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 driver.navigate().to("http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx");
 //driver.manage().window().maximize();
 
 driver.findElement(By.id("ContentHolder_lbSelectionMode_I")).click();
 driver.findElement(By.id("ContentHolder_lbSelectionMode_DDD_L_LBI1T0")).click();
 
 Thread.sleep(5000);
  
 //  Perform Multiple Select 
 Actions builder = new Actions(driver);
 WebElement select = driver.findElement(By.id("ContentHolder_lbFeatures_LBT"));
 List<WebElement> options = select.findElements(By.tagName("td"));
 System.out.println(options.size());
 Action multipleSelect = builder.keyDown(Keys.CONTROL)
  .click(options.get(2))
  .click(options.get(4))
  .click(options.get(6))
  .build();
 multipleSelect.perform();

 driver.close(); 
 
   }
}

output

Upon Executing the Script, the items would be selected as displayed above and the size of the list box would also be printed on console.
selenium_ide_188

Selenium Mouse Actions

Mouse Actions

Sometimes we would be in a situation to perform some complex mouse events such as double click, right click , hover over etc. Below are some of the key mouse actions that one would come across in most of the applications.
  • Click - Perform a Click. We can also perform a click based on coordinates.
  • contextClick - Performs a context click/right click on an element or based on the coordinates
  • doubleClick - Performs a double click on the webelement or based on the coordinates. If left empty it performs double click on the current location.
  • mouseDown - Performs a mouse down action on an element or based on co-ordinates.
  • mouseMove - Performs a mouse move action on an element orbased on co-ordinates.
  • mouseUp - Releases the mouse usually followed by mouse down action and acts based on co-ordinates.
 
void click(WebElement onElement)
void contextClick(WebElement onElement)
void doubleClick(WebElement onElement)
void mouseDown(WebElement onElement)
void mouseUp(WebElement onElement)
void mouseMove(WebElement toElement)
void mouseMove(WebElement toElement, long xOffset, long yOffset)

Selenium Keyboard Actions

Keyboard Actions

Sometimes we would be in a situation to input some key combinations. Eg - pressing ctrl key or Shift key. Below are the methods to interact with keyboard actions.
  • sendKeys - Sends keys to the keyboard representation in the browser. Special keys that are not text, represented as Keys are recognized both as part of sequences of characters, or individually.
  • pressKey - Press a key on the keyboard that is NOT text. The keys such as function keys "F1","F2" or "Tab" or "Control" etc. If keyToPress is a sequence of characters, different driver implementations may choose to throw an exception or to read only the first character in the sequence.
  • releaseKey - Release a key on the keyboard after executing the keypress event. It is usually holds good for non text characters.
Below are the syntax to call keyboard functions using selenium WebDriver.
 
void sendKeys(java.lang.CharSequence keysToSend)
void pressKey(java.lang.CharSequence keyToPress)
void releaseKey(java.lang.CharSequence keyToRelease)

Selenium Drag & Drop

Drag & Drop

As a tester we might be in a situation to perform a 'Drag & drop' operation. We will perform a drag and drop operation by picking up a tree grid that is available for us on http://www.keenthemes.com/preview/metronic/templates/admin/ui_tree.html. In the below example, we would like to drag an element 'Disable Node' from 'initially open' folder to 'Parent Node' Folder.
selenium_ide_185
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

public class webdriverdemo
{
  public static void main(String[] args) throws InterruptedException
  {
 WebDriver driver = new FirefoxDriver();

 //Puts a Implicit wait, Will wait for 10 seconds before throwing exception
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

 //Launch website
 driver.navigate().to("http://www.keenthemes.com/preview/metronic/templates/admin/ui_tree.html");
 driver.manage().window().maximize();
  
  WebElement From = driver.findElement(By.xpath(".//*[@id='j3_7']/a"));
 WebElement To = driver.findElement(By.xpath(".//*[@id='j3_1']/a"));
 Actions builder = new Actions(driver);
 Action dragAndDrop = builder.clickAndHold(From)
   .moveToElement(To)
   .release(To)
   .build();
 dragAndDrop.perform();
 
 driver.close(); 
 
   }
}

Output

After performing the drag-drop operation the output would be as shown below.
selenium_ide_186

Selenium Synchronization

Synchronization

To Synchronize between script execution and application we need to wait after performing appropriate actions. Let us look at the ways to achieve the same.

THREAD.SLEEP

Thread.Sleep is a static wait and it is not good way to use in script as it's sleep without condition.
Thread.Sleep(1000); //Will wait for 1 second.

EXPLICIT WAITS

An explicit wait, waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on object once it is visible.
WebDriver driver = new FirefoxDriver();
driver.get("Enter an URL"S);
WebElement DynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

IMPLICIT WAIT

Implicit wait is used, if Web Driver cannot find the object immediately because of its unavailability. The WebDriver will wait for specified implicit wait time and it will not try to find the element again during the specified time period. Once the specified time limit is crossed, webdriver will try to search the element once again for one last time. If succeeds proceeds with the execution but if failed it throws exception. This is kind of global wait which means this wait is applicable for the entire driver. Hence hardcoding this wait for longer timeperiod will hamper the script execution time.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Enter an URL");
WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));

FLUENT WAIT

FluentWait is used when a webelement can appear in 5 seconds or even it can take 90 seconds. In such instance we define the maximum amount of time to wait for a condition, as well as the frequency with which to check the existance of the object condition.
Let us say we will 60 seconds for an element to be available on the page but checking its presence once in every 10 seconds.
Wait wait = new FluentWait(driver)
  .withTimeout(60, SECONDS)
  .pollingEvery(10, SECONDS)
  .ignoring(NoSuchElementException.class);
WebElement dynamicelement = wait.until(new Function<webdriver,webElement>() 
{
  public WebElement apply(WebDriver driver) 
  {
  return driver.findElement(By.id("dynamicelement"));
  }
 }
);

Selenium Drop Down Interaction

Drop Down Interaction

In this section, we will understand how to interact with Drop Down Boxes. We can select an option using 'selectByVisibleText' or 'selectByIndex' or 'selectByValue' methods.
Let us understand, how to interact with check box using - http://www.calculator.net/interest-calculator.html. We can also check if the drop down box is selected/enabled/Visible.
selenium_ide_182
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class webdriverdemo
{
  public static void main(String[] args) throws InterruptedException
  {
 WebDriver driver = new FirefoxDriver();

 //Puts a Implicit wait, Will wait for 10 seconds before throwing exception
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


 //Launch website
 driver.navigate().to("http://www.calculator.net/interest-calculator.html");
 driver.manage().window().maximize();
  
    // Selecting an item from Drop Down list Box
 Select dropdown = new Select(driver.findElement(By.id("ccompound")));
 dropdown.selectByVisibleText("continuously");
 
 //  you can also use dropdown.selectByIndex(1) to select second element as index starts with 0.
 //  You can also use dropdown.selectByValue("annually");    
        
    System.out.println("The Output of the IsSelected " + driver.findElement(By.id("ccompound")).isSelected());
    System.out.println("The Output of the IsEnabled " + driver.findElement(By.id("ccompound")).isEnabled());
    System.out.println("The Output of the IsDisplayed " + driver.findElement(By.id("ccompound")).isDisplayed());
    
    driver.close(); 
 
   }
}

Output

Upon execution, the drop down is set with the specified value and the output of the commands are displayed in the console.
selenium_ide_184