Your ultimate guide

Handling Keyboard Actions using Selenium with Java

Keyboard Actions:
    When we want to use Mouse or Keyboard actions we should create an 'Actions' class object.

    Syntax: Actions object = new Actions(browser_object);
    Example: Actions act = new Actions(driver);

Method for Action Class:
    perform(): This method is used to execute the action.

The Keyboard interface has the below-mentioned methods:
sendKeys(KeyToSend): Sends a series of keystrokes onto the element.
Example: actions.sendKeys(Keys.DOWN).perform();
Keys.(DOWN, LEFT, RIGHT, UP, ENTER, DELETE, END, ESCAPE, F1-F12, NUMPAD0-NUMPAD9, INSERT, PAGE_DOWN, PAGE_UP, SEMICOLON, SPACE, SUBTRACT, MULTIPLY, ADD, DIVIDE, EQUALS, TAB, SHIFT)
- keyDown(theKey): Sends a key press Without releasing it.
        Example: action.keyDown(Keys.SHIFT).perform();
- keyUp(theKey): Performs a key release.
        Example: action.keyUp(Keys.SHIFT).perform();



Example program:
            class KeyboardAct
            {
                public static void main(String args[])
                {
                    System.setProperty("webdriver.gekco.driver", "./geckodriver.exe");
                    WebDriver driver = new FirefoxDriver();
                    driver.get("https://www.google.com");

                    WebElement searchBox =  driver.findElement(By.name("q"));
                    
                    Actions action = new Actions(driver);
                    action.moveToElement(searchBox)
                                .keyDown(searchBox, Keys.SHIFT)
                                .sendKeys(searchBox, "pokemon")
                                .keyUp(searchBox, Keys.SHIFT)
                                .pause(3000)
                                .sendKeys(Keys.DOWN)
                                .pause(3000)
                                .sendKeys(Keys.ENTER)
                                .perform();
                }
            } 

- Next Page: Select Multiple items in the dropdown

No comments:

Post a Comment