Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Access HTML Source Code Using Python Selenium



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)
Updated on: 2020-10-26T06:29:21+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements