Get HTML with JavaScript Rendered Source Code 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: 2021-02-02T11:44:58+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements