Quick Contact

    What is Action Class

    The Action class is user-facing API for emulating complex user action events. The Webdriver use the Action Class to perform keyboard events and mouse events such as drag and drop or clicking multiple elements while holding down the Control key. The Action class Implements builder pattern, in which a complex object is constructed that can be further used to create different representation of same object. The action events are found in org.openqa.selenium.interactions.Actions class.

    Here is the code snippet for using actions:

    • Configure the Action

      Actions builder = new Actions(driver);

    • To focus on element using webdriver

      builder .moveToElement(element).perform();

    • To click on the element to focus

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

    Perform method is used here to execute the action. The sequence of actions should be minimal.

    Example:

    package automationFramework;
    import java.util.concurrent.TimeUnit; 
    import org.openqa.selenium.*;
    import org.openqa.selenium.interactions.Actions; 
    public class mouseHover{
    public static WebDriver driver;
    public static void main(String[] args) { 
    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    
    driver.get("http://www.onlinestore.toolsqa.wpengine.com");
    
    WebElement element = driver.findElement(By.linkText("Product Category"));
    
    Actions action = new Actions(driver); 
    action.moveToElement(element).build().perform(); 
    driver.findElement(By.linkText("iPads")).click();
    
    }
    }
    
    What Can We Do With Action Class

    Selenium action classes enable to perform advanced activities such as Right-click, Mouse Hover, Pressing any keys on the keyboard, Double click, Click and Hold, Releasing the pressed keys on the keyboard, Scrolling, Drag and Drop. These advanced activities lower the burden of complex codes of the programming languages and allow to just call the methods for the respective activities. To use Actions class, we just need to import the

    org.openqa.selenium.interactions.Actions class
    Keyboard Interactions using Actions API

    In keyboard interaction, normally we consider events such as scrolling the element and focusing on it. With the help of Action API, keyboard interactions are easier now. In Advanced User Interactions API, absolute interaction with element is possible either by clicking on element or sending a Keys.TAB before sending text.

    Actions Class Method for Keyboard Interaction
    • keyDown(Keys modifierKey): The keyDown(Keys modifierKey) method takes the modifier Keys as parameter (Shift, Alt and Control Keys – that modifies the purpose of other keys, hence the name). It is used to simulate the action of pressing a modifier key, without releasing. The expected values for the keyDown() method are – Keys.SHIFT, Keys.ALT and Keys.CONTROL only, passing key other than these results in IllegalArgumentException.
    • keyDown(WebElement element, Keys modifierKey): This another implementation of keyDown() method in which the modifier key press action is performed on a WebElement.
    • keyUp(Keys modifierKey): The keyUp() method is used to simulate the modifier key-up or key-release action. This method follows a preceeding key press action.
    • keyUp(WebElement element, Keys modifierKey): This implementation of keyUp() method performs the key-release action on a web element.
    • sendKeys(CharSequence KeysToSend): The sendKeys(CharSequence KeysToSend) method is used to send a sequence of keys to a currently focussed web element. Here, we need to note that it is different from the webElement.sendKeys() method. The Actions sendKeys(CharSequence KeysToSend) is particularly helpful when dealing with modifier keys as it doesn’t release those keys when passed(resulting in correct behaviour) unlike the webElement.sendKeys() method.
    • sendKeys(WebElement element, CharSequence KeysToSend): This implementation of sendKeys() method is used to send a sequence of keys to a web element.

    Code snippet for Keyboard Actions

    • WebElement to which the keyboard actions are performed
      WebElement textBoxElement = driver.findElement(By Locator of textBoxElement);
    • Creating object of Actions class
      Actions builder = new Actions(driver);
    • Generating an action to type a text in CAPS
      Action typeInCAPS = builder.keyDown(textBoxElement, Keys.SHIFT) 
                   .sendKeys(textBoxElement, "artOfTesting")
                   .keyUp(textBoxElement, Keys.SHIFT)
                   .build();
    • Performing the typeInCAPS action
      typeInCAPS.perform();
    Mouse Interactions using Actions API

    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.

    Actions Class Method for Mouse Interactions
    • click(): This method is used to click at the current mouse pointer position. It is particularly useful when used with other mouse and keyboard events, generating composite actions.
    • click(WebElement webElement): This method is used to click at the middle of a web element passed as parameter to the click() method.
    • clickAndHold(): The clickAndHold() method is used to perform the click method without releasing the mouse button.
    • clickAndHold(WebElement onElement): This method performs the click method without releasing the mouse button over a web element.
    • contextClick(): This method is used to perform the right click operation(context-click) at the current mouse position.
    • contextClick(WebElement onElement): This method performs the right click operation at a particular web element.
    • doubleClick(): This method performs double click operation at a current mouse position.
    • doubleClick(WebElement onElement): Performs the double click operation at a particular web element.
    • dragAndDrop(WebElement fromElement, WebElement toElement): This is a utility method to perform the dragAndDrop operation directly wherein, we can pass the source element and the target element as parameter.
    • dragAndDropBy(WebElement fromElement, int xOffset, int yOffset): This method is a variation of dragAndDrop(fromElement, toElement) in which instead of passing the target element as parameter, we pass the x and y offsets. The method clicks the source web element and then releases at the x and y offsets.
    • moveByOffset(int xOffset, int yOffset): This method is used to move the mouse pointer to a particular position based on the x and y offsets passed as parameter.
    • moveToElement(WebElement toElement): This method is used to move the mouse pointer to a web element passed as parameter.
    • moveToElement(WebElement toElement, int xOffset, int yOffset): This method moves the mouse pointer by the given x and y offsets from the top-left corner of the specified web element.
    • release(): This method releases the pressed left mouse button at the current mouse pointer position.
    • release(WebElement onElement): This method release the pressed left mouse button at a particular web element.

    Code snippet for a Mouse Action

    • WebElement which needs to be right clicked
      WebElement rtClickElement = driver.findElement(By Locator of rtClickElement);
    • Generating an Action to perform context click or right click
      Actions rightClickAction = new Actions(driver).contextClick(rtClickElement);
    • Performing the right click Action generated
      rightClickAction.build().perform();
    • If you want to handle drag and drop event, then you
      can use following code

      Actions builder = new Actions(driver);
          WebElement dragElement=driver.findElement(By.id(“draggable”)); 
          WebElement dropElement=driver.findElement(By.id(“droppable”));
    • To hold the drag element and then move it to drop element location
      Action dragDrop = builder.clickAndHold(dragElement).moveToElement(dropElement).b uild();
    • To Execute the drag and drop Action
      dragDrop.perform();
    • If you want to click on menu option in mouse hover menu, then follow this code:
      Actions builder = new Actions(driver);
          WebElement menu = driver.findElement(By.id(“menu”));
          WebElement menuoption =
          driver.findElement(By.id(“menuoption”));
    • Move to the main menu option and then sub-option
      Action element= builder.moveToElement(menu).moveToElement(menuoption).build();
    • To Execute the Action
      element.perform();

    It’s evident from the above examples that using “Actions API” in Webdriver simplifies input interactions. In fact some events can be only handled by Action API e.g. Drag and drop.

    Code snippet to right click an element

    Actions action = new Actions(driver);
    WebElement element = driver.findElement(By.id("elementId")); action.contextClick(element).perform();
    

    Here, it is instantiating an object of Actions class. After that, it pass the WebElement to be right clicked as parameter to the contestClick() method present in the Actions class. Then, it call the perform() method to perform the generated action.

    Sample code to right click an element

    For the demonstration of the right click action, it will be launching Sample Site for Selenium Learning. Then on right-click a textbox, its context menu will get displayed, asserting that right click action is successfully performed.

    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 RightClick {
    
    public static void main(String[] args) throws InterruptedException{
    WebDriver driver = new FirefoxDriver();
    
    //Launching Sample site
    
    driver.get("http://artoftesting.com/sampleSiteForSelenium.html
    ");
    
    //Right click in the TextBox
    Actions action = new Actions(driver);
    WebElement searchBox = driver.findElement(By.id("fname"));
    action.contextClick(searchBox).perform();
    
    //Thread.sleep just for user to notice the event Thread.sleep(3000);
    
    //Closing the driver instance 
    driver.quit();
    
    }
    }
    
    Code snippet to double click an element
    Actions action = new Actions(driver);
    WebElement element = driver.findElement(By.id("elementId")); action.doubleClick(element).perform();
    

    Here, it is instantiating an object of Actions class. After that, it pass the WebElement to be double clicked as parameter to the doubleClick() method present in the Actions class. Then, call the perform() method to perform the generated action.

    Sample code to double click an element

    For the demonstration of the double click action, it will be launching Sample Site for Selenium Learning. Then it will double click the button on which the text “Double-click to generate alert box” is written. After that an alet box will appear, asserting that double-click action is successfully performed.

    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 DoubleClick {
     
    public static void main(String[] args) throws InterruptedException{
    WebDriver driver = new FirefoxDriver();
    
    //Launching sample website 
    driver.get(http://artoftesting.com/sampleSiteForSelenium.
    html);
    
    driver.manage().window().maximize();
    
    //Double click the button to launch an alertbox 
    Actions action = new Actions(driver);
    WebElement btn = driver.findElement(By.id("dblClkBtn"));
    action.doubleClick(btn).perform();
    //Thread.sleep just for user to notice the event Thread.sleep(3000);
    //Closing the driver instance 
    driver.quit();
    
    }
    }
    
    Example to show how to use Actions class with doubleClick() and perform() methods to double click on element.
    import java.io.IOException;
    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; 
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;
    
    public class DoubleClick { 
    WebDriver driver; 
    @BeforeTest
    public void setup() throws Exception { 
    driver =new FirefoxDriver(); 
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.get("http://only-testing-blog.blogspot.in/2014/09/selectable.html");
    
    }
    
    @Test
    public void doubleClick_Button() throws IOException, 
    InterruptedException {
    WebElement ele = 
    driver.findElement(By.xpath("//button[contains(.,'Double-Click Me To See Alert')]"));
    
    //To generate double click action on "Double-Click Me To See Alert" button.
    Actions action = new Actions(driver); 
    action.doubleClick(ele); action.perform();
    
    Thread.sleep(3000);
    String alert_message = driver.switchTo().alert().getText(); 
    driver.switchTo().alert().accept(); 
    System.out.println(alert_message);
    }
    }
    

    On run this code, It will double click on “Double-Click Me To See Alert”. Rest of code Is to handle alert generated by button double click. So this Is the way to double click on any element In selenium webdriver test.

    Mouse Hover and Mouse Movement with Action

    In order to perform mouse hover actions, all of the actions need to be chain which to achieve in one go. The WebDriver need to be move to the parent element that has child elements and click on the child element. With the object of the Actions class, Webdriver moves to the main menu and then to the sub menu and click on it.

    Few of the scenarios are:

    • Mouse hover actions on an element using Actions Class:

      Example:

      WebElementele = driver.findElement(By.xpath("xpath"));
              //Create object 'action' of an Actions class Actions action = new Actions(driver);
              //Mouseover on an element action.moveToElement(ele).perform();
      
    • Mouse hover actions on a sub-element using Actions Class:

      Example:

      //Main Menu 
                 	WebElementmainMenu =
                  driver.findElement(By.linkText("main_menu_link"));
                  //Create object 'action' of an Actions class 
                  Actions actions = new Actions(driver);
                  //To mouseover on main menu 
                  actions.moveToElement(mainMenu);
      //Sub Menu
      
      WebElementsubMenu = 
      driver.findElement(By.linkText("sub_menu_link"));
      //To mouseover on sub menu actions.moveToElement(subMenu);
      
      //build() method is used to compile all the actions into a single step
      actions.click().build().perform();
      

    Example to Handle Mouseover Action Using Selenium Actions Class:

    	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::l i[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();
    
    }
    }
    
    Finding Coordinates of a Web Object

    Any software web element has its own position on page and generally it is measured in x and y pixels and known as x y coordinates of element. x pixels means horizontal position on page from left side and y pixels means vertical position on software web page from top side. In selenium WebDriver software testing tool, x y coordinates of element can be get by using Point class.

    Example:

    importjava.util.concurrent.TimeUnit; 
    	importorg.openqa.selenium.By; 
    	importorg.openqa.selenium.Point; 
    	importorg.openqa.selenium.WebDriver; 
    	importorg.openqa.selenium.WebElement; 
    	importorg.openqa.selenium.firefox.FirefoxDriver; 
    	importorg.testng.annotations.BeforeTest; 
    	importorg.testng.annotations.Test;
    public class xyCoordinates { 
    WebDriver driver;
    public void setup() throws Exception { 
    driver =new FirefoxDriver(); 
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.get("http://only-testing- 
    blog.blogspot.in/2014/09/selectable.html");
    }
    public void getCoordinates() throws Exception {
    //Locate element for which you wants to retrieve x y coordinates.
    
    WebElement Image = 
    driver.findElement(By.xpath("//img[@border='0']"));
    
    //Used points class to get x and y coordinates of element. 
    Point point = Image.getLocation();
    intxcord = point.getX();
    System.out.println("Element's Position from left side Is "+xcord +" pixels.");
    intycord = point.getY();
    System.out.println("Element's Position from top side Is "+ycord +" pixels.");
    
    }
    }
    

    Output:

    Element's Position from left side Is 76 pixels. Element's Position from top side Is 740 pixels.
    Drag and Drop Action

    In some applications, a situation may be face to automate drag and drop an item from one location to another location. These could not be achieve by using basic elements. The Actions class has two methods that support Drag and Drop.

    • dragAndDrop:

      Syntax:

      Actions.dragAndDrop(Sourcelocator, Destinationlocator)

      First parameter “Sourcelocator” is the element which need to drag
      Second parameter “Destinationlocator” is the element on which need to drop the first element

    • dragAndDropBy:

      Syntax:

      Actions.dragAndDropBy(Sourcelocator, x-axis pixel of Destinationlocator, y-axis pixel of Destinationlocator)
      First parameter “Sourcelocator” is the element which need to drag
      The second parameter is x-axis pixel value of the 2nd element on which need to drop the first element.
      The third parameter is y-axis pixel value of the 2nd element on which need to drop the first element

    Example:

    importorg.openqa.selenium.By; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.WebElement; importorg.openqa.selenium.chrome.ChromeDriver; importorg.openqa.selenium.interactions.Actions; importorg.testng.annotations.Test;
    
    public class DragAndDrop { WebDriver driver;
    @Test
    public void DragnDrop()
    {
    System.setProperty("webdriver.chrome.driver"," E://Selenium//Selenium_Jars//chromedriver.exe ");
    
    driver= new ChromeDriver(); 
    driver.get("http://www.ducatindia.com/test/drag_drop.html");
    
    
    //Element which needs to drag.
    WebElement 
    From=driver.findElement(By.xpath("//*[@id='credit2']/a"));
    
    //Element on which need to drop.
    WebElement To=driver.findElement(By.xpath("//*[@id='bank']/li"));
    
    
    //Using Action class for drag and drop. 
    Actions act=new Actions(driver);
    
    //Dragged and dropped. 
    act.dragAndDrop(From, To).build().perform();
    
    }
    }
    

    In the above code we launch the given URL in Firefox browser and then drag the BANK element and drop on the DEBIT SIDE block through dragAndDropmethod as explained below

    • First, we capture the 1st element which we need to drag in variable “From.”
      WebElement From=driver.findElement(By.xpath("//*[@id='credit2']/a"));
      
    • Second, we capture the 2nd element on which we need to drop the 1st element in variable “To”.
      WebElement To=driver.findElement(By.xpath("//*[@id='bank']/li"));
    • Third, we create object of Actions class as we use methods of Actions class.
      Actions act=new Actions(driver);
    • For drag and drop element dragAndDrop method of Actions class is used and passes the parameters as the first element(Sourcelocator) “From” and the second element(Destinationlocator) “To”. Below line will drag the 1st element and drop it on the 2nd element.
      act.dragAndDrop(From, To).build().perform();

    Example: There is a Checklist on the left side and there are four sub menus with the name of DragAndDrop-[1-3]. We will login to this website and then drag DragAndDrop-1 to DragAndDrop-4 of the left side sub menu.

    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.Action; 
    import org.openqa.selenium.interactions.Actions;
     
    public class DragAndDrop {
    public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    String URL = "http://sandbox.checklist.com/account/"; 
    driver.get(URL);
    driver.findElement(By.name("j_username")).sendKeys("Username");
    
    driver.findElement(By.name("j_password")).sendKeys("Password);
    driver.findElement(By.name("login")).click();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
    WebElement From = driver.findElement(By.xpath(".//*[@id='userChecklists']
    /li[1]/a/span"));
    
    
    WebElement To = driver.findElement(By.xpath(".//*[@id='userChecklists']/l i[4]/a/span"));
    Actions builder = new Actions(driver);
    Action dragAndDrop = builder.clickAndHold(From)
    .moveToElement(To)
    .release(To)
    .build(); 
    dragAndDrop.perform();
    }
    }
    
    Robot Class

    Sometime in testing process it is required to control mouse and keyboard to connect with windows. For example to handle pop-ups, file upload and download. These windows applications are not handled by Selenium Webdriver.

    To handle these pop-ups there is a Robot Class which interacts with OS pop/ups.

    Role of Robot Class
    • To simulate Mouse and Keyboard events
    • Support selenium Webdriver to download or upload a file.
    Initialization in scripts

    Robot Class is part of java.awt.package.

    There are two packages required to import for Robot Class.

    import java.awt.AWTException; 
    import java.awt.Robot;

    Create object of Robot Class

    Robot robot= new Robot();

    Popular methods used in Robot class are

    • .keyPress();- This is used to press any key.

      For example-robot.keyPress(KeyEvent.VK_UP) : It will press UP key in the keyboard.

    • .keyRelease();- This is used to release the press key of keyboard.

      For example- robot.keyRelease(KeyEvent.VK_CAPS_LOCK);:It will release the pressed capslock key in the keyboard.

    • .mousePress();-This is used to press the left button of mouse.

      For Example-robot.mousePress(InputEvent.BUTTON1_MASK);

    • .mouseRelease();- This is used to release the pressed button of mouse.

      For Example-robot.mouseRelease(InputEvent.BUTTON1_MASK);

    • .mouseMove(); This will move the mouse pointer to the X and Y co-ordinates. Co-ordinates of elements are passsed in mouseMove();.
      robot.mouseMove(coordinates.getX(), coordinates.getY());

    For example, if the task is to type ‘A’ (caps+a) using keyboard event. The code will be like

    Robot robot= new Robot();
    
    
    //press CTRL+a
    
    
    robot.keyPress(KeyEvent.VK_CONTROL);
    
    
    Robot.keyPress(KeyEvent.VK_a);
    
    
    //release CTRL+a
    
    
    robot.keyPress(KeyEvent.VK_CONTROL);
    
    
    Robot.keyPress(keyEvent.VK_a);
    
    File upload using Robot Class

    Common steps to upload the file using Robot class are

    1. Copy the path of file which is to be uploaded.
    2. Click on upload button.
    3. Paste the path using Control+V and press enter.
    Disadvantages of Robot Class

    There are few disadvantages of Robot framework

    • Mouse or keyboard event will only works on current instance of window.it is difficult to switch among different screen or windows. For example- A code is executing any robot event but the code execution is moved to other window, in this case Mouse or keyboard event will still remain on previous window.
    • Some methods like mouseMove() is also depends on screen resolutions. So it might be happen that code will not work on other machine.
    Summary
    • The Webdriver use the Action Class to perform keyboard events and mouse events such as drag and drop or clicking multiple elements while holding down the Control key
    • Selenium action classes enable to perform advanced activities such as Right-click, Mouse Hover, Pressing any keys on the keyboard, Double click, Click and Hold, Releasing the pressed keys on the keyboard, Scrolling, Drag and Drop
    • Any software web element has its own position on page and generally it is measured in x and y pixels and known as x y coordinates of element

    Copyright 1999- Ducat Creative, All rights reserved.