How can I print the HTML source of a WebElement in Selenium WebDriver using Python?

How can I print the HTML source of a WebElement in Selenium WebDriver using Python?

I’m using the Python bindings to run Selenium WebDriver:

from selenium import webdriver
wd = webdriver.Firefox()

I know I can grab a webelement like so:

elem = wd.find_element_by_css_selector('#my-id')

And I know I can get the full page source with…

wd.page_source

But is there a way to get the “element source”?

elem.source # ← returns the HTML as a string

The Selenium WebDriver documentation for Python is basically non-existent, and I don’t see anything in the code that seems to enable that functionality.

What is the best way to access the HTML of an element (and its children)?

You can read the innerHTML attribute to get the source of the content of the element or outerHTML for the source with the current element.

Python:

element.get_attribute(‘innerHTML’) Java:

elem.getAttribute(“innerHTML”); C#:

element.GetAttribute(“innerHTML”); Ruby:

element.attribute(“innerHTML”) JavaScript:

element.getAttribute(‘innerHTML’);

PHP:

$element->getAttribute(‘innerHTML’);

It was tested and worked with the ChromeDriver.

Another approach is to use execute_script to run JavaScript code that extracts the inner HTML of the element.

from selenium import webdriver

wd = webdriver.Firefox()
wd.get('https://www.example.com')
elem = wd.find_element_by_css_selector('#my-id')
elem_html = wd.execute_script('return arguments[0].innerHTML;', elem)
print(elem_html)
wd.quit()

You can use the get_attribute(‘outerHTML’) method to get the outer HTML of a WebElement, including the element itself and its children.

from selenium import webdriver

wd = webdriver.Firefox()
wd.get('https://www.example.com')
elem = wd.find_element_by_css_selector('#my-id')
elem_html = elem.get_attribute('outerHTML')
print(elem_html)
wd.quit()