How to simulate pressing enter in html text input with Selenium?

SeleniumAutomation TestingTesting ToolsHTML

We can simulate pressing enter in the html text input box with Selenium webdriver. We shall take the help of sendKeys method and pass Keys.ENTER as an argument to the method. Besides, we can pass Keys.RETURN as an argument to the method to perform the same task.

Also, we have to import org.openqa.selenium.Keys package to the code for using the Keys class. Let us press ENTER/RETURN after entering some text inside the below input box.

Example

Code Implementation with Keys.ENTER.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class PressEnter{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.id("gsc-i-id1"));
      l.sendKeys("Selenium");
      // press enter with sendKeys method and pass Keys.ENTER
      l.sendKeys(Keys.ENTER);
      driver.close();
   }
}

Code Implementation with Keys.RETURN.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class PressReturn{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.id("gsc-i-id1"));
      l.sendKeys("Selenium");
      // press enter with sendKeys method and pass Keys.RETURN
      l.sendKeys(Keys.RETURN);
      driver.close();
   }
}
raja
Published on 26-Oct-2020 07:33:33
Advertisements