Contents
Selenium Python – Get the inner HTML of an element
In this tutorial, you will learn how to get the inner HTML of an element using Selenium in Python.
To get the inner HTML of an element in Selenium Python, find the element, then call get_attribute()
method of the element object and pass "innerHTML"
as argument. The get_attribute()
method returns the inner HTML of the element.
The following code snippet returns the inner HTML of the element
object.
element.get_attribute("innerHTML")
The element
is of type WebElement.
Examples
In the following examples, we shall consider loading the following HTML file via the driver object.
index.html
<html>
<body>
<h2>Hello User!</h2>
<p id="msg">This is my <strong>first</strong> paragraph. This is a sample text. Welcome!</p>
<div id="mydiv">
<div class="child">Child 1</div>
<div class="child">Child 2</div>
</div>
</body>
</html>
1. Get the inner HTML of para element with id=”msg”
In the following program, we initialize a webdriver, navigate to a specific URL (index.html) that is running on a local server, get the inner HTML of the element with id="msg"
, and print the inner HTML to the standard output.
Python Program
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
# Setup chrome driver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Navigate to the url
driver.get('http://127.0.0.1:5500/index.html')
# Get the element
element = driver.find_element(By.ID, "msg")
# Get inner HTML of the element
html = element.get_attribute("innerHTML")
print(html)
# Close the driver
driver.quit()
Output

2. Get the inner HTML of div element with id=”mydiv”
In this example, we are going to get the inner HTML of a div element whose id="mydiv"
.
Python Program
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
# Setup chrome driver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Navigate to the url
driver.get('http://127.0.0.1:5500/index.html')
# Get the element
element = driver.find_element(By.XPATH, '//div[@id="mydiv"]')
# Get inner HTML of the element
html = element.get_attribute("innerHTML")
print(html)
# Close the driver
driver.quit()
Output

Summary
In this Python Selenium tutorial, we have given instructions on how to get the inner HTML of an element using get_attribute()
method of WebElement class, with example programs.