How can I extract and print the HTML content of a webpage by using selenium?

21    Asked by DavidPiper in QA Testing , Asked on May 8, 2024

 I am currently engaged in a particular task that is related to automating a project by using selenium and I need to extract and print the HTML content of a specific webpage. How can I achieve this by using selenium in Python? 

Answered by David EDWARDS

 In the context of selenium, here is the example given of how you can achieve this by using the selenium in Python programming language:-


From selenium import webdriver
From selenium.webdriver.chrome.service import Service
From selenium.webdriver.common.by import By
From selenium.webdriver.support.ui import WebDriverWait
From selenium.webdriver.support import expected_conditions as EC
# Set up the Chrome WebDriver (assuming you have downloaded the Chrome WebDriver executable)
Chrome_driver_path = “path_to_chromedriver.exe” # Update with your Chrome WebDriver path
Service = Service(chrome_driver_path) 
  Driver = webdriver.Chrome(service=service)Try:

    # Navigate to the desired webpage

      Driver.get(https://www.example.com)

    # Wait for the page to fully load

      WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, “body”)))

    # Get the HTML content of the page

      Html_content = driver.page_source
    # Print the HTML content
    Print(html_content)
Finally:
    # Close the WebDriver
    Driver.quit()

Here is the example given in java programming language:-

Import org.openqa.selenium.WebDriver;
Import org.openqa.selenium.chrome.ChromeDriver;
Public class PrintHTMLContent {
    Public static void main(String[] args) {
        // Set the path to the Chrome WebDriver executable
        System.setProperty(“webdriver.chrome.driver”, “path_to_chromedriver.exe”); // Update with your Chrome WebDriver path
        // Initialize the Chrome WebDriver
        WebDriver driver = new ChromeDriver();
        Try {
            // Navigate to the desired webpage
            Driver.get(https://www.example.com);
            // Get the HTML content of the page
            String htmlContent = driver.getPageSource();
            // Print the HTML content
            System.out.println(htmlContent);
        } finally {
            // Close the WebDriver
            Driver.quit();
        }
    }
}

Here is the example given by using HTML:-




<meta</span> charset=”UTF-8”>

<meta</span> name=”viewport” content=”width=device-width, initial-scale=1.0”>

Scroll to Button




 

   


Your Answer