Reading:  

Getting started with Selenium


Selenium WebDriver's Advanced User Interactions API

The Selenium WebDriver's Advanced User Interactions API allows us to perform operations from keyboard events and simple mouse events to complex events such as dragging-and-dropping, holding a key and then performing mouse operations by using the Actions class. 

User interface (UI) testing is a process used to test if the application is functioning correctly. UI testing can be performed manually by a human tester, or it can be performed automatically with the use of a software program.

We need to interact with the application using some basic actions or even some advanced user action by developing user-defined functions for which there are no predefined commands.

The different kinds of actions on GUI objects are:

Text Box Interaction:

To interact with text box:

  • Enter values into a text box by using the 'sendkeys' method.
  • To retrieve text from a text box using the getAttribute("value") command as we've seen in previous chapter.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestWebDriver {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
	      // Wait for 5 seconds before throwing exception
	      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
	      
	      // launch xe.com home page
	      driver.navigate().to("http://www.xe.com/");
	      
	      //To maximize the window
	      driver.manage().window().maximize();
	      
	      // To get the value of from_var hidden field 
	      String result = driver.findElement(By.xpath("//input[@id='from_var']")).getAttribute("value");
	      
	      // Finally print the result
	      System.out.println("from_var holds : " + result);
	      
	      // Close the session
	      driver.close();

	}

}

 

Output:

The output of the above script is as shown below.

 

 

Radio Button Interaction:

To interact with Radio Buttons:

To select and unselect a radio button option using the 'click' method .

To understand how to interact with radio buttons using: http://codepad.org/. We can also check if a radio button is selected or enabled as shown below example.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestWebDriver {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
	      // Wait for 5 seconds before throwing exception
	      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
	      
	      // launch xe.com home page
	      driver.navigate().to("http://codepad.org/");
	      
	      //To maximize the window
	      driver.manage().window().maximize();
	      
	      // To get the value of from_var hidden field 
	      Boolean result = driver.findElement(By.name("lang")).isSelected();
	      
	      // Finally print the result
	      System.out.println("Lang C option selected by default: " + result);
	      
	      String cpp_xpath = ".//*[@id='editor']/table/tbody/tr[2]/td[1]/nobr[2]/label/input";
	      driver.findElement(By.xpath(cpp_xpath)).click();
	      result = driver.findElement(By.xpath(cpp_xpath)).isSelected();
	      
	      System.out.println("Lang C++ option selected by click: " + result);
	      
	      
	      // Close the session
	      driver.close();
	}
}
 

Result:

Radio button interaction

Check Box Interaction: 

Interaction with Check Boxes is very similar to Radio buttons:

We can select a check box or un check it using the 'click' method, and other method that applies to radio buttons, applies to checkboxes too such as isSelected(), isDisplayed(), isEnabled() etc.

 

Interacting with Select (Drop down boxes)

Interaction with drop down boxes is as simple. Consider the following example

WebElement dd = driver.findElement(By.tagName("select"));
List<WebElement> allOptions = dd.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
    System.out.println(String.format("Value of option: %s", option.getAttribute("value")));
    option.click();
}

Some handy functions for drop down element are

dropdown.selectByValue("Some value"); // To Select the options that have a value matching with the given argument by the user.
dropdown.selectByVisibleText("Some value"); // To Select all options that display text matching the given argument. It will not look for any index or value, it will try to match the VisibleText
dropdown.selectByIndex(1); // To Select the option based on the index given by the user.

And then there are some other handy methods too such as 

dropdown.deselectByIndex(index); // To Deselect the option at the given index. 
dropdown.deselectByValue(value); // To Deselect all options that have a value matching the given argument.
dropdown.deselectByVisibleText(text);  // To Deselect all options that display text matching the given argument.
dropdown.deselectAll(); To Clear all selected entries for the drop down. This method will work when SELECT has multiple attribute declared <select multiple="multiple">, else NotImplementedExaception is thrown

Synchronization:

It is a process which support for more than one component to work parallel with Each other.

Types of Synchronization are

ImplicitWait:


An implicit wait is to tell WebDriver to wait for certain amount of time when trying to find an element/if the elements is not immediately available.

By default implicit wait setting is 0. After we define the implicit wait, it will set for the life of the WebDriver object instance. 

Syntax: driver.manage.TimeOuts.implicitwait(6,Timeunit.SECONDS);

Example:

WebDriver driver = new FirefoxDriver();
// wait for 15 seconds before throwing an exception
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("www.google.com.au");

 

ExplicitWait:

 

used to define a wait statement for certain condition to be satisfied until the specified timeout period. If the Webdriver finds the element within the timeout period the code will get executed. 

Example:


WebDriver driver = new FirefoxDriver();driver.get("URL Here");
WebElement el = (new WebDriverWait(driver, 15)).until(ExpectedConditions.presenceOfElementLocated(By.id("Element")));
 

FluentWait:

 

used to define the maximum amount of time to wait for a condition, as well as the frequency with which to check for the condition.

Example:

Let us say we will 30 seconds for an element to be available on the page, but we will check its available once in every 15 seconds.

Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(15, SECONDS) .ignoring(NoSuchElementException.class);   
WebElement dynamicelement = wait.until(new Function<webdriver,webElement>(){      
public WebElement apply(WebDriver driver){     
return driver.findElement(By.id("dynamicelement"));     
}  
});

Static wait

Thread.sleep(2000); // sleeps for 2 seconds, without any conditions and halting a script may not always be a great idea


Selenium-Drag & Drop: 

We have a web application where we need to drag an item from one location to another location. These kinds of complex actions are not available in basic element properties. Automating rich web application is interesting, as it involves advanced user interactions. Thankfully Selenium has provided a separate “Actions” class to handle these advanced user interactions.

WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();

 

Above will drag draggable element and drop to target container

Selenium-Keyboard Actions:

In keyboard interaction, here we consider events such as scrolling the element and focusing on it. Action API, helps to make keyboard interactions are easy. In Advanced User Interactions API, absolute interaction with element is possible either by clicking on element or by using sendKeys.

 The three methods of Keyboard interface are:

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.

Void sendKeys(CharSequence... keysToSend) : Same as existing sendKeys() method in Webdriver

pressKey: Click on key on the keyboard that is NOT text. The keys such as function keys "F1", "F2", "Tab", "Control", etc.

Void pressKey: Sends a key press only, without releasing it. Should only be implemented for modifier keys (Control, Alt and Shift)

releaseKey: Release a key on the keyboard after executing the keypress event. It usually holds good for non-text characters.

To releases a modifier key:

Void releaseKey(Keys keyToRelease) –

Selenium-Mouse Actions:

In mouse actions we use current location of the element as a standard. First action will be relative to the location of the standard element, the next action will be relative to the location of the mouse at the end of the last action, etc.

The Mouse interface includes the following methods: 

  • Click: To click on element. 
    Syntax: Void click (WebElement onElement) 
  • contextClick: Performs a context-click (right click) on an element.
    Syntax: Void contextClick(WebElement onElement) 
  • doubleClick: To double clicks on Element.
    Syntax: Void double click (WebElement onElement) 
  • mouseUp: To releases the mouse button on an element.
    Syntax: Void mouseUp(WebElement onElement) 
  • mouseDown: To holds down the left mouse button on an element.
    Syntax: Void mouseDown(WebElement onElement)
  • mouseMove: To move from the current location to another element
    Void mosueMove(WebElement onElement ,long xOffset, long yOffset ) : Move (from the current location) to new coordinates.
    Syntax: Void mouseMove(WebElement onElement)

How to find all links on a web page using selenium

Source

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
	 
public class AllLinks {
		 
	public static void main(String[] args){
		   
	      WebDriver driver = new FirefoxDriver();
	      driver.navigate().to("http://www.codepad.org");
	      java.util.List cpLinks = driver.findElements(By.tagName("a"));
	      System.out.println("Number of Links found on codepad " + cpLinks.size());
	      // let's iterate on link collection array
	      for (int i = 0; i<cpLinks.size(); i=i+1) {
	         System.out.println("Link Text for link number " + (i+1)+" is : "+ cpLinks.get(i).getText());
	 	}
	}
}

Result:

Result will look something like this  

How to get all links on a page using Selenium web driver

 

In next chapter we will learn about basic test techniques

 

Description

This tutorial will get you started with Selenium. This tutorial is subdivided into 11 chapters. 

  1. Overview
  2. IDE
  3. Environment Setup
  4. Remote Control
  5. Selenese Commands
  6. Webdriver
  7. Locators
  8. User Interactions
  9. Test design techniques
  10. TestNG
  11. Grid

 

 

 

* freelancer contributed



Environment

A PC capable of running selenium

Prerequisites

A basic idea of what Software Testing is.

Audience

People who wish to get started with Selenium

Learning Objectives

You will learn ins and outs of Selenium which includes downloading, installing and using Selenium.

Author: Subject Coach
Added on: 10th Feb 2015

You must be logged in as Student to ask a Question.

None just yet!