dev dev - 7 months ago 200
Java Question

Send caps text to a text box using Robot class & Selenium WebDriver

How to send capital text to a text box using Robot class and Selenium WebDriver.

Answer

You need to do two things to:

1- First to get focus to the textfield, where you want to enter the value, like this:

driver.findElement(By.xpath("//xpath of the element")).sendKeys("")// id or class can be used as locators too.

2- Then use 'Robot class' to send values to the field (using CAPSLOCK or SHIFT keys for changing the letters to uppercase).

Try this code. It works for sending "HELLO" (all caps) in Google.com's search field using "CAPSLOCK":

//Navigating to the site
driver.get("http://www.google.com");

//To get the focus on the searchbox (NOT ENTERING ANYTHING)
driver.findElement(By.id("gbqfq")).sendKeys("");

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);
robot.keyPress(KeyEvent.VK_H);
robot.keyRelease(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_E);
robot.keyRelease(KeyEvent.VK_E);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_L);
robot.keyRelease(KeyEvent.VK_L);
robot.keyPress(KeyEvent.VK_O);
robot.keyRelease(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);

OR you can try using "SHIFT" as below:

    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_SHIFT);
    robot.keyPress(KeyEvent.VK_H);
    robot.keyRelease(KeyEvent.VK_H);
    robot.keyPress(KeyEvent.VK_E);
    robot.keyRelease(KeyEvent.VK_E);
    robot.keyPress(KeyEvent.VK_L);
    robot.keyRelease(KeyEvent.VK_L);
    robot.keyPress(KeyEvent.VK_L);
    robot.keyRelease(KeyEvent.VK_L);
    robot.keyPress(KeyEvent.VK_O);
    robot.keyRelease(KeyEvent.VK_O);
    robot.keyRelease(KeyEvent.VK_SHIFT);
Comments