我們如何使用 JavaScript 執行程式在 Selenium 中單擊和向 Web 元素中輸入資料?
我們可以使用 JavaScript 執行程式在 Selenium webdriver 中單擊和向 Web 元素中輸入資料。selenium 可以藉助 executeScript 方法執行 JavaScript 命令。
要單擊元素,executeScript 方法的引數是 - arguments[0].click(); 和 Web 元素定位器。
語法
WebElement l = driver.findElement(By.className("gsc-input")); JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("arguments[0].click();", l);
然後,要向編輯框中輸入資料,傳遞給 executeScript 方法的引數是 – Web 元素定位器。值
語法
j.executeScript("document.getElementsByName('gsc-i-id1')[0].value= 'Java'");
讓我們嘗試單擊下面的編輯框並向其中輸入資料。
示例
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 JavaScrptVal{ 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/"); WebElement l = driver.findElement(By.name("q")); //JavaScript Executor to click element JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("arguments[0].click();", l); //JavaScript Executor to enter text j.executeScript("document.getElementsByName('q')[0].value= 'Java'"); String s = l.getAttribute("value"); System.out.println("Value entered is: " + p); driver.close(); } }
輸出
廣告