Open In App

In Selenium WebDriver, use Python to obtain the WebElement’s HTML source?

The article focuses on discussing how to use Python to obtain the WebElement’s HTML source.

Prerequisites:



Selenium Python Installation: Using Selenium Webdriver, one can obtain the HTML source of any WebElement.

What is an HTML Source?



HTML Source is described as the HTML code that underlies a certain web element on a web page.

What is Web Element?

Web Element is anything that is displayed on the webpage.

Steps to Retrieve the HTML Source of a Web Element

The source of the HTML Element can be found from the innerHTML attribute. The content between the opening tag and the ending tag is the value of the innerHTML attribute of a DOM element.

This is the method which is used in Python to get the innerHTML attribute:

element.get_attribute(‘innerHTML’)

The complete code for the program to extract the HTML source is the following:




# Python program to retrieve HTML
# source code of the web element
from selenium import webdriver
import time
  
# string constants
PATH = r"C:\Users\VRINDA\Desktop\chromedriver_win32\chromedriver.exe"
  
# chrome options
options = webdriver.ChromeOptions();
options.add_experimental_option('excludeSwitches', ['enable-logging']);
  
try:
    browser = webdriver.Chrome(PATH, options=options);
    browser.get(URL);
    browser.maximize_window();
    element = browser.find_element_by_id("contact");
    print(element.get_attribute('innerHTML'))
    time.sleep(6);
finally:
    browser.quit()

Ouput:

This is the output received on the console printing the innerHTML attribute of the element.

This is the part of the webpage of which the innerHTML is calculated :

Element of the webpage


Article Tags :