如何使用 Selenium 在 HTML 文本输入框中模拟按回车键?
seleniumautomation testingtesting toolshtml更新于 2026/2/10 12:28:17
我们可以使用 Selenium webdriver 在 HTML 文本输入框中模拟按回车键。我们需要借助 sendKeys 方法,并将 Keys.ENTER 作为参数传递给该方法。此外,我们还可以将 Keys.RETURN 作为参数传递给该方法,以执行相同的任务。
此外,为了使用 Keys 类,我们需要将 org.openqa.selenium.Keys 包导入到代码中。在下面的输入框中输入一些文本后,按下 ENTER/RETURN 键。

示例
使用 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.cainiaomax.com/about/about_careers.htm");
// 识别元素
WebElement l=driver.findElement(By.id("gsc-i-id1"));
l.sendKeys("Selenium");
// 使用 sendKeys 方法按下回车键并传递 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.cainiaomax.com/about/about_careers.htm");
// 识别元素
WebElement l=driver.findElement(By.id("gsc-i-id1"));
l.sendKeys("Selenium");
// 使用 sendKeys 方法按下回车键并传递 Keys.RETURN
l.sendKeys(Keys.RETURN);
driver.close();
}
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

