Keyboard Actions in Selenium

  

In Selenium WebDriver, keyboard events such as pressing keys like EnterTabShiftCtrl, etc., are handled using the Actions class. The Actions class provides methods to simulate complex user interactions, including keyboard operations.


Common Keyboard Methods in Actions Class


MethodDescription
keyDown(Keys key)Presses a key without releasing it
keyUp(Keys key)Releases a pressed key
sendKeys(CharSequence keysToSend)Sends a sequence of keystrokes to the currently focused element


Example Use Cases

  • Simulating Ctrl + A (Select All), Ctrl + C (Copy), Ctrl + V (Paste)

  • Sending Enter or Tab

  • Typing into input boxes


Selenium Java Script: Keyboard Events using Actions Class

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 KeyboardEventsExample {
    public static void main(String[] args) {
        // Set the path to chromedriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();

        // Open a demo form
        driver.get("https://www.w3schools.com/html/html_forms.asp");

        // Locate input element
        WebElement inputBox = driver.findElement(By.xpath("//input[@name='firstname']"));

        // Create Actions object
        Actions actions = new Actions(driver);

        // Click input box, type name in uppercase using SHIFT, then press TAB to go to next field
        actions
            .click(inputBox)
            .keyDown(Keys.SHIFT)
            .sendKeys("john")
            .keyUp(Keys.SHIFT)
            .sendKeys(Keys.TAB)
            .sendKeys("doe") // typing in next input box
            .build()
            .perform();

        // Close browser
        driver.quit();
    }
}

Explanation

  • keyDown(Keys.SHIFT) → Press and hold the SHIFT key.

  • sendKeys("john") → Type JOHN (in uppercase).

  • keyUp(Keys.SHIFT) → Release the SHIFT key.

  • sendKeys(Keys.TAB) → Press TAB to move to the next input.

  • sendKeys("doe") → Type "doe" in the next field.


Important Points

  • Use Keys.ENTER, Keys.ESCAPE, Keys.ARROW_DOWN, etc., for simulating different key presses.

  • Always use build().perform() to compile and run the full action chain.

No comments:

Post a Comment