Chúng ta có thể mô phỏng nhấn phím Enter trong ô input text HTML với Selenium WebDriver. Sử dụng phương thức sendKeys và truyền Keys.ENTER làm tham số. Ngoài ra, cũng có thể truyền Keys.RETURN để thực hiện tương tự.
Cần import package org.openqa.selenium.Keys để dùng class Keys. Ví dụ nhấn ENTER/RETURN sau khi nhập văn bản vào ô input dưới đây:

Ví dụ
Triển khai với 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");
// Xác định phần tử
WebElement l = driver.findElement(By.id("gsc-i-id1"));
l.sendKeys("Selenium");
// Nhấn Enter với sendKeys và Keys.ENTER
l.sendKeys(Keys.ENTER);
driver.close();
}
}
Triển khai với 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");
// Xác định phần tử
WebElement l = driver.findElement(By.id("gsc-i-id1"));
l.sendKeys("Selenium");
// Nhấn Enter với sendKeys và Keys.RETURN
l.sendKeys(Keys.RETURN);
driver.close();
}
}
Lưu ý: Keys.ENTER và Keys.RETURN thường cho kết quả giống nhau trên hầu hết trình duyệt. Có thể dùng Keys.chord(Keys.CONTROL, "a") để tổ hợp phím (Ctrl+A, Ctrl+C, v.v.).