下面的代码片段显示了如何在Selenium WebDriver中执行JavaScript。
WebDriver driver = new ChromeDriver();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript("alert('hello world');");
}
1. WebDriver示例
在此示例中,它使用WebDriver
加载“ google.com”,并在以后执行一个简单的alert ()
。
JavaScriptExample.java
package com.mkyong.test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class JavaScriptExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"/Users/mkyong/Downloads/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1024,768");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
driver.get("http://google.com/");
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver)
.executeScript("alert('hello world');");
}
}
}
输出量
参考文献
标签: javascript 硒
翻译自: https://mkyong.com/selenium/how-to-execute-javascript-in-selenium-webdriver/