
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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(); } }
Advertisements