How to extract html through Javascript executor?

孤街浪徒 提交于 2021-02-10 13:27:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!