Using Selenium Actions Class for Handling Keyboard and Mouse Events

Selenium has the built-in ability to handle various types of keyboard and mouse events. In this post, we’ll teach you about the Selenium Actions class which enables user interaction with the web applications.

To perform mouse operations on a website, first of all, we’ve to launch the browser and then navigate to the URL of the site. The entire control of browser as well as the application is in the reference variable of type WebDriver.

The WebDriver reference variable can identify any web element which is present on the page. But it doesn’t have the ability to handle the following mouse events.

  • Mouse actions on some elements.
  • Drag and drop.
  • Right-click, and so on.

Hence, you should clearly know that the WebDriver reference variable alone can’t work. So, to perform the mouse actions, we need to make use of the Selenium Actions class.

Here is the list of topics that we are going to take up in this post.

Also, if you are planning for a Selenium interview, then you must read the below post.

Let’s not wait anymore and proceed for reading the post.

How to Use Selenium Actions Class for Handling Keyboard and Mouse Events?

How to use Selenium Actions Class – Syntax?

First, we’ll initialize the WebDriver instance followed by creating the action builder object. Please check out from the below code.

WebDriver driver = new FirefoxDriver();

WebElement ele = driver.findElement(By.xpath(…………));

Actions ref = new Actions (driver);

ref.movetoElement(ele);

ref.click().build().perform();

In the above code, we are executing more than one actions. So we need to use <build()> method to compile all these into a single step.

 

What are the methods available in Selenium Actions Class?

Following is the list of most commonly used keyboard and mouse events provided by the Selenium Actions class.

MethodDescription
<clickAndHold()>Clicks at the present mouse location (without releasing).
<contextClick()>Makes a context-click at the existing mouse location.
<doubleClick()>It performs a double-click at the existing mouse location.
<dragAndDrop(source, target)>Invokes click-and-hold at the source location and moves to the location of the target element before releasing the mouse.

Parameters:

source– element to grab.

target– element to release.

<dragAndDropBy(source, x-offset, y-offset)>Performs click-and-hold at the source location, shifts by a given offset, then frees the mouse.

Parameters:

source- element to grab.

<xOffset>- to shift horizontally.

<yOffset>- to shift vertically.

<keyDown(modifier_key)>Invokes a modifier key press. Does not free the modifier key – subsequent actions may assume it as pressed.

Parameters:

modifier_key – any of the modifier keys (Keys.ALT, Keys.SHIFT, or Keys.CONTROL)

<keyUp(modifier _key)>Frees up a mouse press.

Parameters:

modifier_key – any of the modifier keys (Keys.ALT, Keys.SHIFT, or Keys.CONTROL)

<moveByOffset(x-offset, y-offset)>Shifts the mouse from its current position (or 0,0) by the given offset.

Parameters:

<x-offset> – Sets the horizontal offset. A (-ve) value means shifting the mouse to the left.

<y-offset> – Sets the vertical offset. A (-ve) value means shifting the mouse to the up.

<moveToElement(toElement)>It shifts the mouse to the center of the element.

Parameters:

<toElement> – target element.

<release()>Frees up the depressed left mouse button at the existing mouse location.
<sendKeys(onElement, charsequence)>Transmits a series of keystrokes onto the element.

Parameters:

<onElement> – an element that will receive the keystrokes, usually a text field.

<charsequence> – any string value representing the sequence of keystrokes to be sent.

 

Handle mouseover action using Selenium Actions Class.

Let’s take an example of mouseover action using the Selenium Actions class. In this example, we’ll showcase the automation of the mouseover actions on the following website.

  • www.myntra.com

Note: If you wish to use a different site for Selenium testing, then read the below blog post.

Our test script will execute the below steps.

  1. Open the browser.
  2. Navigate to the given URL (www.myntra.com).
  3. Mouse Hover on the Men’s tab present in the top navigational bar.
  4. Select the <Bags and Bag-packs> option from the Accessories tab.
  5. Move to the first item displayed on the web page and add it to the cart.
  6. Lastly, remove the same item from the cart.
  7. Close the browser.

Selenium Actions Class Example-1.

package com.techbeamers.testing;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class MouseHoverExample {

   public static void main(String[] args) throws Exception {

      // Initialize WebDriver
      WebDriver driver = new FirefoxDriver();

      // Wait For Page To Load
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // Go to URL
      driver.get("http://www.myntra.com/");

      // Maximize Window
      driver.manage().window().maximize();

      // Mouse Over On " Men link "
      Actions act = new Actions(driver);
      By testlink = By.linkText("Men");
      WebElement test = driver.findElement(testlink);
      act.moveToElement(test).build().perform();

      // Click on " bags & backpacks " link
      driver.findElement(By.linkText("Bags & Backpacks")).click();

      // Click on the categories - Bag-packs
      driver.findElement(By.xpath("//*[text()='Categories']//following::li[1]/label")).click();

      // Mouse Hover on the 1st bag
      Actions sel = new Actions(driver);
      sel.moveToElement(driver.findElement(By.xpath("//ul[@class='results small']/li[1]"))).build().perform();

      // Click on the "Add to Bag" icon of the 1st bag
      driver.findElement(By.xpath("//ul[@class='results small']/li[1]/div[1]//div")).click();

      // Hover over the shopping bag icon present on the top navigation bar
      Actions mov = new Actions(driver);
      mov.moveToElement(driver.findElement(By.xpath("//a[contains(@class, 'cart')]//div"))).click().build().perform();

      // Click on the remove icon
      driver.findElement(By.xpath("(//span[@data-hint='REMOVE FROM BAG'])[1]")).click();

      // Closing current driver window
      driver.close();
   }
}

 

Execute a Sequence of actions using Selenium Actions Class.

Suppose we want to execute a sequence of actions on the same element. We can achieve this by using the <build()> method. Let’s demonstrate this with an example.

Please check out the use case and the steps covered in the sample code.

  1. Open the browser.
  2. Navigate to the given URL (www.facebook.com).
  3. Fetch the reference for Web Element Email (textbox).
  4. Enter the text “hello” into the textbox after converting it into Capital letters.
  5. Highlight the text in the textbox by clicking on it.
  6. Lastly, right-click to open the context menu.
  7. Close the browser.

Our Selenium Actions class sample will run the above steps and call them using the <build()> method.

The sample code for the given scenario is as follows.

Selenium Actions Class Example-2.

package com.techbeamers.testing;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class MultipleActionsExample {

   public static void main(String[] args) throws Exception {

      // Initialize WebDriver
      WebDriver driver = new FirefoxDriver();

      // Wait For Page To Load
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

      // Go to URL
      driver.get("http://www.facebook.com/");

      // Maximize Window
      driver.manage().window().maximize();

      // get the reference for Web Element Email
      WebElement userName = driver.findElement(By.id("email"));

      // Handling Multiple Actions
      Actions act = new Actions(driver);
      Action seriesOfActions = act.moveToElement(userName).click().keyDown(userName, Keys.SHIFT)
            .sendKeys(userName, "hello").keyUp(userName, Keys.SHIFT).doubleClick(userName).contextClick().build();
      seriesOfActions.perform();

      // Closing current driver window
      driver.close();
   }
}

 

Final Word.

We most of the time try to pick a topic that can help in your work. Also, we intend to teach you skills that matter the most in your job profile. That’s why we came up with this blog post on using Selenium Actions class.

It would be great to hear from you if this post helped you in learning Selenium. So do let us know about your experience.

Also, you can submit a request for any topic of your choice. We’ll include it in our plan and add to the priority list.

If you liked the post, then please don’t miss to share it with friends and on social media.
Keep Learning,

TechBeamers.