Accessing HTML source code using Python Selenium.

SeleniumAutomation TestingTesting ToolsHTMLPython

We can access HTML source code with Selenium webdriver. We can take the help of the page_source method and print the value obtained from it in the console.

Syntax

src = driver.page_source

We can also access the HTML source code with the help of Javascript commands in Selenium. We shall take the help of execute_script method and pass the command return document.body.innerHTML as a parameter to the method.

Syntax

h = driver.execute_script("return document.body.innerHTML;")

Example

Code Implementation.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# access HTML source code with page_source method
s = driver.page_source
print(s)

Code Implementation with Javascript Executor.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# access HTML source code with Javascript command
h = driver.execute_script("return document.body.innerHTML")
print(h)
raja
Published on 26-Oct-2020 06:29:07
Advertisements