Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Run Opera Driver in Selenium Using Java?
Next article icon

How to get innerHTML of whole page in selenium java driver?

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When automating web applications with Selenium WebDriver in Java, it's often necessary to retrieve the entire HTML content of a webpage. This can be useful for testing purposes, data extraction, or validating the structure of the page.

Selenium WebDriver provides a straightforward way to access the innerHTML of the entire page using Java. By fetching the HTML content, you can analyze or manipulate it programmatically.

Prerequisite

We will be required 3 main things:

  1. Java Development Kit (JDK) installed.
  2. Browser Driver (e.g., ChromeDriver for Chrome).
  3. IDE like Eclipse or IntelliJ IDEA.

Dependencies for Selenium

We will be required to have dependencies for selenium, for that, we will add dependencies in the XML file.

pom.xml

XML
<dependencies>   <!-- Selenium Java Dependency -->   <dependency>     <groupId>org.seleniumhq.selenium</groupId>     <artifactId>selenium-java</artifactId>     <version>4.21.0</version>   </dependency> </dependencies> 

Example

Index.html

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Sample Page</title> </head> <body>     <h1>Welcome to My Website</h1>     <p>This is a simple paragraph on my web page.</p>     <div>         <h2>Section 1</h2>         <p>This is some content in section 1.</p>     </div>     <div>         <h2>Section 2</h2>         <p>This is some content in section 2.</p>     </div> </body> </html> 

Application.java

Java
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;  public class Application {     public static void main(String[] args) {         // Set the path to your WebDriver executable         System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");          // Initialize ChromeDriver         WebDriver driver = new ChromeDriver();          try {             // Load the local HTML file             driver.get("file:///path_to_your_html_file/index.html");              // Option 1: Get the entire page source             String pageSource = driver.getPageSource();             System.out.println("Page Source:");             System.out.println(pageSource);              // Option 2: Get innerHTML of the body using JavaScriptExecutor             JavascriptExecutor js = (JavascriptExecutor) driver;             String bodyInnerHTML = (String) js.executeScript("return document.body.innerHTML;");             System.out.println("\nBody InnerHTML:");             System.out.println(bodyInnerHTML);          } finally {             // Close the browser             driver.quit();         }     } } 

Output

Output
Output

GetInnerHTMLExample.java

Java
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;  public class GetInnerHTMLExample {     public static void main(String[] args) {         // Set the path to your WebDriver executable         System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");          // Initialize ChromeDriver         WebDriver driver = new ChromeDriver();          try {             // Load the local HTML file             driver.get("https://www.geeksforgeeks.org");              // Option 1: Get the entire page source             String pageSource = driver.getPageSource();             System.out.println("Page Source:");             System.out.println(pageSource);              // Option 2: Get innerHTML of the body using JavaScriptExecutor             JavascriptExecutor js = (JavascriptExecutor) driver;             String bodyInnerHTML = (String) js.executeScript("return document.body.innerHTML;");             System.out.println("\nBody InnerHTML:");             System.out.println(bodyInnerHTML);          } finally {             // Close the browser             driver.quit();         }     } } 

Output

Output
Output

Conclusion

Retrieving the innerHTML of the whole page in Selenium Java is a simple and effective method for accessing the complete HTML structure. By utilizing JavaScriptExecutor in Selenium, you can easily extract the HTML content of the webpage. This is particularly useful for debugging or validating the HTML code during test automation. Using Selenium WebDriver allows you to automate this process efficiently across different browsers.


Next Article
How to Run Opera Driver in Selenium Using Java?

A

agrawalvishesh9271
Improve
Article Tags :
  • Selenium

Similar Reads

  • How to get userAgent information in Selenium Web driver?
    When utilizing Selenium WebDriver for the automation of web tests, it is frequently essential to retrieve the user agent string of a browser. The user agent conveys details regarding the browser and operating system, which can be instrumental in assessing how a web application performs in diverse en
    2 min read
  • How to Run Opera Driver in Selenium Using Java?
    Selenium is a well-known software used for software testing purposes. Selenium consists of three parts. One is Selenium IDE, one is Selenium Webdriver & the last one is Selenium Grid. Among these Selenium Webdriver is the most important one. Using Webdriver online website testing can be done. Th
    3 min read
  • How to Run Gecko Driver in Selenium Using Java?
    Selenium is a well-known software used for software testing purposes. It consists of three parts: Selenium IDE, Selenium WebDriver, and Selenium Grid. Selenium WebDriver is the most important. Using WebDriver, online website testing can be done. There are three main WebDriver implementations: Chrome
    5 min read
  • How to Run Safari Driver in Selenium Using Java?
    Selenium is a well-known software used for software testing purposes. Selenium consists of three parts: Selenium IDE, Selenium Webdriver, and Selenium Grid. Among these, Selenium Webdriver is the most important one. Using Webdriver, online website testing can be done. There are three main Webdrivers
    4 min read
  • How to Open a Browser in Headless Mode in Selenium using Java?
    Headless testing has become a significant trend in modern web automation, offering numerous advantages for developers and testers. In Selenium, running tests in headless mode allows browsers to operate without the graphical user interface (GUI). This article delves into the concept of headless brows
    6 min read
  • How to get the total number of checkboxes in a page using Selenium?
    In the world of automated testing, Selenium is a powerful tool that helps automate web browsers. One common task during web testing is determining the number of specific elements on a page, such as checkboxes. This can be useful for validating the presence and quantity of checkboxes on a form or any
    3 min read
  • How to convert commands recorded in Selenium IDE to Java?
    Selenium IDE is a powerful browser extension allowing you to record and replay interactions easily. However, for more advanced testing and integration with frameworks like JUnit, it is essential to convert recorded commands into Java code. In this guide, we will walk you through converting Selenium
    6 min read
  • How to Get All Available Links on the Page using Selenium in Java?
    Selenium is an open-source Web-Automation tool that is used to automate web Browser Testing. The major advantage of using selenium is, that it supports all major web browsers and works on all major Operating Systems, and it supports writing scripts on various languages such as Java,  JavaScript, C#
    2 min read
  • How to Handle iframe in Selenium with Java?
    In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed. Table of Content What are iframes in Selenium?Difference between frame and iframe in SeleniumSteps to Identify a Frame on a Page?How to Switch Over the Elements in ifram
    11 min read
  • How to get an attribute value from a href link in Selenium java?
    When working with Selenium WebDriver in Java, automating web interactions often involves handling hyperlinks. A common task is to extract the attribute value from a <a> tag, specifically the href attribute, which contains the link's destination URL. Extracting this href value allows you to ver
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences