Site icon

Handle mouse & keyboard events in Selenium (Actions class)

Code: Handle mouse & keyboard events – Selenium Actions class:

package org.learn;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class MouseKeyboardEvents {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "C:\\work\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.amazon.com/");

        // Passing the driver capabilities to Action class
        Actions a = new Actions(driver);

        // Locating a specific web element
        WebElement move = driver.findElement(By.xpath("//a[@id='nav-link-accountList']"));

        // Mouseover an Object using selenium
        a.moveToElement(move).build().perform();

        // Entering "Hello" in Capital letters in Text box
        a.moveToElement(driver.findElement(By.id("twotabsearchtextbox")))
                .click().keyDown(Keys.SHIFT).sendKeys("hello").build().perform();

        // Right clicking an element using Context Click
        a.moveToElement(move).contextClick().build().perform();
    }
}

Output 1 – Handle Mouseover event using selenium

Output 2 – Entering “Hello” in Capital letters in Text box

Output 3 – Right clicking Web Element using Context Click

Exit mobile version