Chúng ta có thể lấy HTML source của một WebElement với Selenium WebDriver. Sử dụng thuộc tính innerHTML để lấy source của phần tử web.
innerHTML là thuộc tính của webelement bằng với văn bản nằm giữa thẻ mở và thẻ đóng. Phương thức get_attribute dùng cho việc này với innerHTML làm tham số.
Cú pháp
s = element.get_attribute('innerHTML')
Có thể lấy HTML source của webelement nhờ Javascript Executor. Sử dụng phương thức execute_script và truyền arguments[0].innerHTML cùng webelement cần lấy source.
Cú pháp
s = driver.find_element_by_id("txt-search")
driver.execute_script("return arguments[0].innerHTML;", s)
Ví dụ HTML của một phần tử. innerHTML sẽ là: You are browsing the best resource for <b>Online Education</b>.

Ví dụ
Triển khai với get_attribute
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# implicit wait
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# Xác định phần tử và lấy innerHTML với get_attribute
l = driver.find_element_by_css_selector("h4")
print("HTML code of element: " + l.get_attribute('innerHTML'))
Triển khai với Javascript Executor
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# implicit wait
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")
# Xác định phần tử và lấy innerHTML với 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)
Kết quả

Lưu ý: Selenium 4 khuyến khích dùng driver.find_element(By.CSS_SELECTOR, "h4") thay cho find_element_by_css_selector (deprecated). Cách dùng JavaScriptExecutor linh hoạt hơn khi cần outerHTML hoặc thao tác DOM phức tạp.