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();
   }
}

輸出

更新於:06-Apr-2021

5 千次 + 瀏覽

開啟你的 事業

完成課程進行認證

開始
廣告
© . All rights reserved.