Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HTML source of 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 are 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)?

like image 672
Chris W. Avatar asked Aug 31 '11 21:08

Chris W.


People also ask

Can Selenium read HTML?

Selenium is a Python module for browser automation. You can use it to grab HTML code, what webpages are made of: HyperText Markup Language (HTML).

What is innerHTML in Selenium?

The innerHTML is an attribute of a webelement which is equal to the content that is present between the starting and ending tag. The getAttribute method is used for this and innerHTML is passed as an argument to the method.


1 Answers

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.

like image 109
Nerijus Avatar answered Sep 22 '22 19:09

Nerijus