02
DecBlack Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook - SCHEDULE CALL
While shopping online, you might have come across several mouse and keyboard events like when you right-click on any of the elements of the web page it performs some action. If you have enabled Grammarly extension on your web browser, you might have noticed that if you double-click on any word, the pop up appears which shows the meaning of the word you have double-clicked.
This feature of acting as the trigger of a click of a mouse or a keypress of a keyboard is done by using Actions class of Selenium. In this blog, we’ll resolve your wandering situation of several events which you have seen on websites.
Proceeding forward, let us talk about Action Class in Selenium.
Action Class is a task automation functionality provided by Selenium’s web driver. It is used for handling events by using Advanced User Interactions API, and action class contain such actions for the execution of such events. In simple words, Action class is an API for performing complex user web interactions like double-click, right-click, etc. Action class is the only way for emulating the keyboard and mouse interactions.
Action class implements the “Builder Pattern,” which is used to separate the construction of a complex object from its representation. Action class also creates a “CompositeAction,” which contains all the actions specified by the method calls.
Fig: methods available in action class
// Configure the Action
Actions action = new Actions(driver);
// To click on the element
action.moveToElement(element).click().perform();
In Selenium, there are two classes available- Action Class and Actions Class.
Actions Class creates composite actions with an aggregation of Selenium WebDriver. WebDriver is used to identify the availability of web-based elements on the web application.
Action Class is an interface which is used to represent single-user interaction to perform a series of action items created by Actions class.
Read: How To Download & Install Selenium IDE & WebDriver
Example differentiating Actions and Action Class-
Drag and Drop Web Elements:
Actions actionseries=new Actions(driver);
WebElement sourceLocation=Wedriver.findElement(By.xpath("Source location locator value"));
WebElement targetLocation=Wedriver.findElement(By.xpath("Target location locator value"));
Action action=actionseries.dragAndDrop(sourceLocation, targetLocation).build();
action.perform();
The syntax for drag and drop
Actions action = new Actions(driver);
action.dragAndDrop(Sourcelocator, Destinationlocator).build().perform();
We can also make it as below:
(new Actions(driver)).dragAndDrop(element, target).perform();
We have also used Webdriver Wait Expected conditions to wait for a frame to be available and then switch to the frame.
The below is the image on which we will perform this operation:
Java Code for this: -
package com.pack.dragndrop; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.Test; public class DragNDropExample { WebDriver driver; @Test public void testDragAndDropExample() { driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.navigate().to("http://jqueryui.com/droppable/"); //Wait for the frame to be available and switch to it WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector(".demo-frame"))); WebElement Sourcelocator = driver.findElement(By.cssSelector(".ui-draggable")); WebElement Destinationlocator = driver.findElement(By.cssSelector(".ui-droppable")); dragAndDrop(Sourcelocator,Destinationlocator); String actualText=driver.findElement(By.cssSelector("#droppable>p")).getText(); Assert.assertEquals(actualText, "Dropped!"); } }
Below is the simple method to perform drag and drop. But before performing, we need to check if both the elements SourceElement and destination elements are available.
public void dragAndDrop(WebElement sourceElement, WebElement destinationElement)
{
(new Actions(driver)).dragAndDrop(sourceElement, destinationElement).perform();
}
}
In a few words, Actions is a Class, and Action is an Interface.
Actions class implement the Action interface. Action interface only one method: perform(). The action method gets the arguments as a constructor, and then implementing class decides what interaction should be done on the webpage. For example, finding an Element, passing keys using sendkeys and highlighting it.
We can implement action actions methods by importing org.openqa.selenium.interactions.Actions and org.openqa.selenium.interactions.Action
Read: What is Selenium Grid? Selenium Grid Tutorials for Beginners
Then configure it by creating an object of Actions class like below:
Actions build = new Actions(driver);
Build.moveToELement(toElement).click().perform();
Actions action=new Actions(driver);
action.moveToElement(element).perform();
action.moveToElement(element).click().perform();
You can perform it by using the build() method. Build method generates a composite action containing all actions so far, which are ready to be performed.
Action action = actions.build();
You can perform it by using the perform() method.
action.perform();
actions.keyDown(element,Keys.SHIFT).sendKeys(TextToBeConvertAndSendInUpperCase).keyUp(Keys.SHIFT).perform();
Let’s go through the description of both keyboard and mouse events of Selenium.
Keyboard Events | |
keyDown() | This method is used to perform a modifier key press when used it makes sure that subsequent interactions can assume it’s kept pressed. Modifier key as a parameter accepts key such as Keys.ALT, Keys.SHIFT, Keys.CONTROL, etc. |
keyUp() | This method is used to perform a modifier key release event. As explained before modifier keys are Keys.ALT, Keys.SHIFT, Keys.CONTROL, etc. |
sendKeys() | This method is used to send a series of keystrokes on to a web element. It accepts two parameters. |
Mouse Events | |
clickAndHold() | This method is used to click and hold (without releasing) on the current object at the current mouse location on a web page. |
contextClick() | This method is used to perform a context-click at the current mouse location on a web page. |
doubleClick() | This method is used to perform a double-click at the current mouse location on a web page. |
dragAndDrop() |
This method is used to perform first click and hold an event on the current object and then move that object to the location of the target web element and release the mouse after that. It accepts two parameters. Read: How to Download and Install Selenium IDE in Firefox? ● Source as a parameter accepts the element location at button down. ● Target, as a parameter, accepts the object to move and release the mouse at the target element. |
dragAndDropBy() |
This method is used to perform click and hold at the location of the source element and then moves off by a given offset (x-offset and y-offset) and then release the mouse. It accepts three parameters. ● Source as a parameter accepts the element location. ● X-offset, as a parameter, accepts the horizontal offset. ● Y-offset, as a parameter, accepts the vertical offset. |
moveByOffset() | This method is used to perform the mouse moves from its current position to given offset (x-offset, y-offset). A negative value of x-offset means moving the mouse left, and a positive value means moving the mouse right. A negative value of y-offset means moving the mouse up, and a positive value means moving the mouse down. |
moveToElement() | This method is used to move the mouse to the middle of the web element. It accepts one parameter, which is the element to move to. |
release() | This method is used to release the depressed left mouse at its current location. |
For a better understanding of the methods mentioned above, let us take an example of Amazon using mouseover action of Selenium Actions class.
The code of the above example will be-
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.amazon.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("Men’s Fashion")).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();
}
}
Other than this, you can create a series of Action and Actions Classes. We are going to implement using build() method.
public static void main(String[] args) {
String baseUrl = "http://www.facebook.com/";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement txtUsername = driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
Action seriesOfActions = builder
.moveToElement(txtUsername)
.click()
.keyDown(txtUsername, Keys.SHIFT)
.sendKeys(txtUsername, "hello")
.keyUp(txtUsername, Keys.SHIFT)
.doubleClick(txtUsername)
.contextClick()
.build();
seriesOfActions.perform();
}
AdvancedUserInteractions API
.doubleClick(), keyUp, dragAndDropBy, contextClick & sendKeys
.In this blog post, we have learned about the action class, the difference between Action and Actions class using Java examples, and the other events which occur in Actions class of Selenium. Hope you enjoyed this piece of content. Happy Learning!
A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
Selenium WebDriver Architecture you Need to Know 7.9k
Page Object Model (POM) with Page Factory in Selenium WebDriver 361.5k
Ultimate Selenium Testing Tutorials For Beginners & Professionals (With Career Path) 2.5k
Learn How To Handle Different Webelements in Selenium 5.5k
What is Xpath in Selenium? How to Write Xpath Selenium? 10.1k
Receive Latest Materials and Offers on Selenium Course
Interviews