Get HTML source of WebElement in Selenium WebDriver using Python Get HTML source of WebElement in Selenium WebDriver using Python python python

Get HTML source of WebElement in Selenium WebDriver using Python


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.


There is not really a straightforward way of getting the HTML source code of a webelement. You will have to use JavaScript. I am not too sure about python bindings, but you can easily do like this in Java. I am sure there must be something similar to JavascriptExecutor class in Python.

 WebElement element = driver.findElement(By.id("foo")); String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);


Sure we can get all HTML source code with this script below in Selenium Python:

elem = driver.find_element_by_xpath("//*")source_code = elem.get_attribute("outerHTML")

If you you want to save it to file:

with open('c:/html_source_code.html', 'w') as f:    f.write(source_code.encode('utf-8'))

I suggest saving to a file because source code is very very long.


matomo