使用 Selenium WebDriver 读取 JavaScript 变量。
我们可以用 Selenium webdriver 读取 Javascript 变量。Selenium 可以借助 executeScript 方法运行 Javascript 命令。作为参数传递要执行的 Javascript 命令到该方法。此外我们必须添加语句 import org.openqa.selenium.JavascriptExecutor 以使用 Javascript。
语法
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("return document.title")让我们通过读取来自 Javascript 变量的值以下页面的浏览器标题。输出应该是 关于tutorialspoint.com的职业 - Tutorialspoint.

例
代码实现
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JavascriptReadValue{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://tutorialspoint.com/about/about_careers.htm")
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// Javascript executor to read value
JavascriptExecutor j = (JavascriptExecutor) driver;
// get the browser title with document.title
String t = (String)j.executeScript("return document.title");
System.out.print("Current page title: " +t);
driver.close();
}
}输出

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