Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Truy xuất mã nguồn HTML bằng Python Selenium


Chúng ta có thể truy xuất mã nguồn HTML với Selenium WebDriver. Sử dụng phương thức page_source và in giá trị lấy được ra console.

Cú pháp

src = driver.page_source

Có thể cũng truy xuất mã nguồn HTML với lệnh JavaScript trong Selenium. Sử dụng phương thức execute_script và truyền lệnh return document.body.innerHTML làm tham số.

Cú pháp

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

Ví dụ

Triển khai mã với page_source.

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")
# Truy xuất HTML source code với page_source method
s = driver.page_source
print(s)

Triển khai mã với 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")
# Truy xuất HTML source code với Javascript command
h = driver.execute_script("return document.body.innerHTML")
print(h)

So sánh: page_source trả về toàn bộ HTML của trang (kể cả head), trong khi document.body.innerHTML chỉ trả về nội dung bên trong thẻ body. Cách dùng JavaScript linh hoạt hơn khi cần lấy HTML của một phần tử cụ thể.