如何使用 Python 和 Selenium 获取页面完整截图?
我们可以使用 Selenium 获取页面的完整截图。在执行任何测试用例时,我们可能会遇到失败的情况。为了跟踪这些失败,我们会捕获出现错误的网页的截图。
在测试用例中,可能由于以下原因导致失败:
- 断言未通过。
- 我们的应用程序和 Selenium 之间存在同步问题。
- 存在超时问题。
- 中间出现警报。
- 无法使用定位器识别元素。
- 实际结果与最终结果不匹配。
为了捕获截图,可以使用 `save_screenshot()` 方法。此方法可以获取整个页面的截图。
语法
driver.save_screenshot("screenshot_t.png")在参数中,我们必须提供截图文件名以及 .png 扩展名。如果使用其他扩展名,则会抛出警告消息,并且无法查看图像。
截图将保存在程序的同一路径中。
示例
获取全页面截图的代码实现。
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to get the screenshot of complete page
driver.save_screenshot("screenshot_tutorialspoint.png")
#to close the browser
driver.close()
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP