使用 Python Selenium 访问 HTML 源代码。
seleniumautomation testingtesting toolshtmlpython更新于 2026/2/10 6:36:17
我们可以使用 Selenium webdriver 访问 HTML 源代码。我们可以借助 page_source 方法并在控制台中打印从该方法获得的值。
语法
src = driver.page_source
我们还可以在 Selenium 中借助 Javascript 命令访问 HTML 源代码。我们将借助 execute_script 方法并将命令 return document.body.innerHTML 作为参数传递给该方法。
语法
h = driver.execute_script("return document.body.innerHTML;")
示例
代码实现。
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")
# 使用 page_source 方法访问 HTML 源代码
s = driver.page_source
print(s)
使用 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")
# 使用 Javascript 命令访问 HTML 源代码
h = driver.execute_script("return document.body.innerHTML")
print(h)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

