如何在不呼叫 sendKeys() 的情況下使用 Selenium 向文字框中輸入文字?
我們可以藉助 JavaScript Executor 在文字框中輸入文字,而無需使用 sendKeys 方法。Selenium 藉助 executeScript 方法執行 JavaScript 命令。
要執行的 JavaScript 命令會作為引數傳遞到此方法。要輸入文字,我們應首先使用 JavaScript 方法 document.getElementById 查詢輸入框。然後我們必須對其應用 value 方法。
讓我們在下面的輸入框中輸入文字 Selenium −

語法
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JsEnterText{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://tutorialspoint.tw/index.htm");
// JavaScript Executor to enter text
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript ("document.getElementById('gsc-i-id1').value='Selenium'");
WebElement l = driver.findElement(By.id("gsc-i-id1"));
String s = l.getAttribute("value");
System.out.println("Value entered is: " + s);
driver.quit();
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP