Get HTML Source of WebElement in Selenium WebDriver using Python.

SeleniumAutomation TestingTesting ToolsHTMLPython

We can get html source of a webelement with Selenium webdriver.We can get the innerHTML attribute to get the source of the web element.

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

Syntax

s = element.get_attribute('innerHTML')

We can obtain the html source of the webelement with the help of Javascript Executor. We shall utilize the execute_script method and pass arguments index.innerHTML and webelement whose html source is to be retrieved to the method.

Syntax

s = driver.find_element_by_id("txt-search")
driver.execute_script("return arguments[0].innerHTML;",s)

Let us see the below html code of an element. The innerHTML of the element shall be − You are browsing the best resource for <b>Online Education</b>.

Example

Code Implementation with get_attribute.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe"
# implicit wait applied
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element and obtain innerHTML with get_attribute
l = driver.find_element_by_css_selector("h4")
print("HTML code of element: " + l.get_attribute('innerHTML'))

Code Implementation with Javascript Executor.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe"
# implicit wait applied
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# to identify element and obtain innerHTML with execute_script
l = driver.find_element_by_css_selector("h4")
h= driver.execute_script("return arguments[0].innerHTML;",l)
print("HTML code of element: " + h)

Output

raja
Published on 26-Oct-2020 11:57:01
Advertisements