sendKeys() 在 Selenium Webdriver 中不起作用
如果在使用 sendKeys 方法时遇到问题,那么我们可以使用 JavaScript 执行器在编辑框中输入文本。Selenium 可以借助 executeScript 方法运行 JavaScript 命令。
要使用的 JavaScript 命令作为参数传递给该方法。要输入文本,我们将首先使用 JavaScript 方法 document.getElementsByClassName 标识编辑字段。然后在它上面应用 value 方法。
让我们尝试在下面的 Google 搜索框中输入文本 tutorialspoint −

语法
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("document.getElementsByName('qwe')[0].value= 'tutorialspoint'");示例
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 SendkysAlternate{
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://www.google.com/");
//identify element
WebElement m =driver.findElement(By.className("gLFyf"));
//JavaScript Executor to enter text
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("document.getElementsByName('q')[0].value= 'tutorialspoint'");
String str = m.getAttribute("value");
System.out.println("Text entered: " + str);
driver.close();
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP