问题
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class oo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","D:\\Java\\Lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://google.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
Object s = js.executeScript("return document.body.innerHTML;",null).toString();
System.out.println(s);
driver.close();
}
}
Above code returns nullPointerException.
Exception in thread "main" java.lang.NullPointerException at java.util.Arrays.stream(Unknown Source) at java.util.stream.Stream.of(Unknown Source) at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:484) at oo.main(oo.java:25)
When I remove optional object parameter, it goes compilation error.
Code:
JavascriptExecutor js = (JavascriptExecutor) driver;
Object s = js.executeScript("return document.body.innerHTML;").toString();
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method executeScript(String, Object[]) in the type JavascriptExecutor is not applicable for the arguments (String)
Using Selenium-server-standalone-3.141.59.jar
回答1:
To extract and print the Page Source through JavascriptExecutor you can use the following (Java based) solution:
Syntax:
String page_source = ((JavascriptExecutor)driver).executeScript("return document.documentElement.innerHTML;").toString(); System.out.println(page_source);
Note: You need to induce a waiter for the page to load completely before extracting the Page Source.
来源:https://stackoverflow.com/questions/53411703/how-to-extract-html-through-javascript-executor