- Selenium Blogs -

What is Actions Class in Selenium and How to use it?

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.

Actions Class in Selenium

Proceeding forward, let us talk about Action Class in Selenium.

What is 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.

Actions Class in Selenium

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.

Actions Class in Selenium

Fig: methods available in action class

Syntax of 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.

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();

How drag and drop elements work in Action Class of Selenium?

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:

Actions Class in Selenium

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

Then configure it by creating an object of Actions class like below:

Actions build = new Actions(driver);
Build.moveToELement(toElement).click().perform();

Misc. Syntax used in Actions Class

How to create an object “action” of Selenium Actions Class: -

Actions action=new Actions(driver);

How to focus on element using WebDriver of Selenium Actions Class: -

action.moveToElement(element).perform();

  • element is the webelement which we capture
  • perform() method is used here to execute the action.

How to click on element using WebDriver of Selenium Actions Class: -

action.moveToElement(element).click().perform();

How to build ActionsSequence using WebDriver of Selenium Actions Class: -

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();

How to perform ActionsSequence using WebDriver of Selenium Actions Class: -

You can perform it by using the perform() method.

action.perform();

How to catch in Actions Class: -

actions.keyDown(element,Keys.SHIFT).sendKeys(TextToBeConvertAndSendInUpperCase).keyUp(Keys.SHIFT).perform();

Keyboard and Mouse Events in Actions Class of Selenium

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.

●      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.

  1. Open the web browser
  2. Navigate to the URL www.amazon.com
  3. Hover the mouse on “Shop by categories” and then on Men’s fashion
  4. Select the Clothing option from the tab
  5. You may move your mouse cursor on any of the item mentioned on the web page or for an assumption, select first item displayed on the web page
  6. Add the item to cart
  7. At last, remove the same item from the cart
  8. Now, close the browser

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();

}

Summary

  • Handling special keyboard and mouse events are done using the AdvancedUserInteractions API.
  • Frequently used Keyword and Mouse Events are doubleClick(), keyUp, dragAndDropBy, contextClick & sendKeys.

Conclusion

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!

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Comments

Search Posts

Reset

Receive Latest Materials and Offers on Selenium Course