How to get html with javascript rendered sourcecode by using Selenium?


We can get HTML with JavaScript rendered source code by using Selenium webdriver. Selenium can execute JavaScript commands with the help of the executeScript method.

JavaScript command to be executed is passed as a parameter to the method. To obtain the HTML, with JavaScript, we shall pass return document.getElementsByTagName('html')[0].innerHTML as a parameter to the executeScript method.

Syntax

JavascriptExecutor j = (JavascriptExecutor) driver;
String s = (String) j.executeScript
(return document.getElementsByTagName('html')[0].innerHTML");

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class HTmlSrcJS{
   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://www.tutorialspoint.com/index.htm ");
      //Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      String s = (String) j.executeScript
      (return document.getElementsByTagName('html')[0].innerHTML");
      System.out.println(s);
      driver.quit();
   }
}

To obtain the HTML, with JavaScript, we can also pass return document.body.innerHTML as a parameter to the executeScript method.

Syntax

JavascriptExecutor j = (JavascriptExecutor) driver;
String s = (String) j.executeScript
(return document.body.innerHTML");

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class HTmlSrcBodyJS{
   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://www.tutorialspoint.com/index.htm ");
      //Javascript Executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      String s = (String) j.executeScript
      (return document.body.innerHTML");
      System.out.println(s);
      driver.quit();
   }
}

Updated on: 02-Feb-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements