TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Selenium Actions Class Events Explained
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

Selenium Actions Class Events Explained

Last updated: Feb 25, 2024 10:45 am
By Meenakshi Agarwal
Share
9 Min Read
Selenium Actions Class for Handling Keyboard and Mouse Events
SHARE

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 web applications.

Contents
Selenium Actions Class MethodsHandle MouseOver ActionSelenium Actions Class Example-1Execute a Sequence of ActionsSelenium Actions Class Example-2

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 the browser as well as the application is in the reference variable of type WebDriver.

The WebDriver reference variable can identify any web element that 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.

Selenium Actions Class – Handle Keyboard and Mouse Events

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

Selenium Actions Class for Handling Keyboard and Mouse Events

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

First, we’ll initialize the WebDriver instance followed by creating the action builder object. Please check out 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 action. So we need to use the <build()> method to compile all these into a single step.

Selenium Actions Class Methods

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

MethodDescription
<clickAndHold()>Clicks at the present mouse location (without releasing).
<contextClick()>Performs click-and-hold at the source location, shifts by a given offset, and then frees the mouse.

Parameters: source- element to grab.
xOffset – to shift horizontally.
yOffset– to shift vertically.
<doubleClick()>It performs a double-click at the existing mouse location.
<dragAndDrop(source, target)>Makes a context click at the existing mouse location.
<dragAndDropBy(source, x-offset, y-offset)>Performs click-and-hold at the source location, shifts by a given offset, and 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

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.

Must Read: Demo Websites for Selenium Testing

Our test script will execute the below steps.

  • Open the browser.
  • Navigate to the given URL (www.myntra.com).
  • Mouse Hover on the Men’s tab is present in the top navigational bar.
  • Select the option from the Accessories tab.
  • Move to the first item displayed on the web page and add it to the cart.
  • Lastly, remove the same item from the cart.
  • 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

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.

  • Open the browser.
  • Navigate to the given URL (www.facebook.com).
  • Fetch the reference for Web Element Email (textbox).
  • Enter the text “hello” into the textbox after converting it into Capital letters.
  • Highlight the text in the textbox by clicking on it.
  • Lastly, right-click to open the context menu.
  • 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 – Selenium Actions Class

We most of the time try to pick a topic that can help in our 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 the 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 it to the priority list.

If you liked the post, then please don’t miss out on sharing it with friends and on social media.

Keep Learning,
TechBeamers

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

TAGGED:Advanced Selenium TutorialSelenium Action Class
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Exception Handling Python Exception Handling
Next Article Most Common QA Interview Questions and Answers for Testers 8 Most Common QA Interview Questions Every Tester Should Know

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x