如何在Selenium WebDriver中执行JavaScript

下面的代码片段显示了如何在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 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);");
	}
		
  }
}

输出量

参考文献

翻译自:
经验分享 程序员 微信小程序 职场和发展