如何使用 Selenium 模擬在 html 文字輸入中按 enter?
我們可以使用 Selenium webdriver 模擬按下 html 文字輸入框中的 enter。我們將使用 sendKeys 方法,並將 Keys.ENTER 作為方法的引數。此外,我們可以將 Keys.RETURN 作為方法的引數來執行相同任務。
此外,我們必須將 org.openqa.selenium.Keys 包匯入程式碼,以便使用 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://tutorialspoint.tw/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();
}
}使用 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://tutorialspoint.tw/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();
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP