How to get HTML source of WebElement in Selenium WebDriver using Python?

Sometimes, we want to get HTML source of WebElement in Selenium WebDriver using Python.

In this article, we’ll look at how to get HTML source of WebElement in Selenium WebDriver using Python.

How to get HTML source of WebElement in Selenium WebDriver using Python?

To get HTML source of WebElement in Selenium WebDriver using Python, we can call the get_attribute method.

For instance, we write

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# ...

element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
print(element.get_attribute("outerHTML"))

to get get the element with ID my-id with

WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))

Then we get the element’s outerHTML property with

element.get_attribute("outerHTML")

to get the returned element‘s HTML.

Conclusion

To get HTML source of WebElement in Selenium WebDriver using Python, we can call the get_attribute method.