How do I use Selenium to press the Enter/Return key on a webpage?
To press the Enter/Return key on a webpage using Selenium WebDriver in Java. You can use Keys.RETURN constant from the Keys enum to simulate pressing the Enter key.
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;
public class EnterKeyPress {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
WebElement element = driver.findElement(By.id("myElementId"));
element.sendKeys(Keys.RETURN);
driver.quit();
}
}
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class EnterKeyPress {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
WebElement element = driver.findElement(By.id("myElementId"));
Actions actions = new Actions(driver);
actions.sendKeys(element, Keys.RETURN).perform();
driver.quit();
}
}
Using JavascriptExecutor: Use the JavascriptExecutor interface to execute JavaScript code that simulates pressing the Enter key.
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class EnterKeyPress {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
WebElement element = driver.findElement(By.id("myElementId"));
((JavascriptExecutor) driver).executeScript("arguments[0].dispatchEvent(new KeyboardEvent('keypress', { 'key': 'Enter' }))", element);
driver.quit();
}
}