如何使用 Python 获取 Selenium 页面中特定元素的屏幕截图?

selenium web driverautomation testingsoftware testing更新于 2026/2/14 11:37:17

我们可以在 Selenium 中获取页面中特定元素的屏幕截图。在执行任何测试用例时,我们可能会遇到特定元素失败的情况。为了查明特定元素的失败原因,我们会尝试截取错误所在的屏幕截图。

元素中可能由于以下原因出现错误 −

  • 如果断言未通过。
  • 如果我们的应用程序与 Selenium 之间存在同步问题。
  • 如果存在超时问题。
  • 如果中间出现警报。
  • 如果无法使用定位器识别元素。
  • 如果实际结果与最终结果不匹配。

可以使用 save_screenshot() 方法截取屏幕截图。此方法截取整个页面的屏幕截图。

没有内置方法来截取元素。为此,我们必须将整个页面的图像裁剪为元素的特定大小。

语法

driver.save_screenshot('screenshot_t.png')

在参数中,我们必须提供屏幕截图文件名以及 .png 扩展名。如果使用其他扩展名,则会引发警告消息,并且无法查看图像。

屏幕截图将保存在程序的同一路径下。

在这里,我们需要借助 Webdriver 中的 location 和 size 方法来裁剪图像。为此,我们需要导入一个 PIL 图像库。它可能是也可能不是标准库的一部分。但是,如果不可用,可以使用 pip install Pillow 命令安装。

每个元素都有一个由 (x, y) 坐标测量的唯一位置。location 方法提供两个值——元素的 x 和 y 坐标。

每个元素都有一个由其高度和宽度定义的尺寸。这些值可以通过 size 方法获取,该方法提供两个值——元素的高度和宽度。

现在开始裁剪图像。

# 获取坐标区
ax = location['x'];
ay = location['y'];
width = location['x']+size['width'];
height = location['y']+size['height'];
# 计算裁剪后的图像尺寸
cropImage = Image.open('screenshot_t.png')
cropImage = cropImage.crop((int(ax), int(ay), int(width), int(height)))
cropImage.save('cropImage.png')

示例

截取特定元素屏幕截图的代码实现。

from selenium import webdriver
from PIL import Image
#浏览器公开一个可执行文件
#通过Selenium测试,我们将调用该可执行文件,然后
#调用实际的浏览器
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# 最大化浏览器窗口
driver.maximize_window()
#获取方法启动URL
driver.get("https://www.tutorialspoint.com/index.htm")
#刷新浏览器
driver.refresh()
#识别要截取屏幕截图的元素
s= driver.find_element_by_xpath("//input[@class='gsc-input']")
#获取元素位置
location = s.location
#获取元素尺寸
size = s.size
#获取完整页面截图
driver.save_screenshot("screenshot_tutorialspoint.png")
#获取 x 轴
x = location['x']
#获取 y 轴
y = location['y']
#获取元素长度
height = location['y']+size['height']
#获取元素宽度
width = location['x']+size['width']
# 打开截取的图像
imgOpen = Image.open("screenshot_tutorialspoint.png")
# 将截取的图像裁剪为该元素的大小
imgOpen = imgOpen.crop((int(x), int(y), int(width), int(height)))
# 保存裁剪后的图像
imgOpen.save("screenshot_tutorialspoint.png")
# 关闭浏览器
driver.close()

相关文章