Selenium屏幕截图技巧:实现自动化截屏并按日期时间格式保存图片

在自动化测试过程中,我们经常需要对测试结果进行截图保存,以便于后续的分析和报告。Selenium WebDriver提供了丰富的屏幕截图功能,可以帮助我们轻松实现这一需求。本文将介绍如何使用Selenium WebDriver进行屏幕截图,并按照日期时间格式保存图片。

python 复制代码
# 导入所需库
from selenium import webdriver

# 创建一个webdriver实例
driver = webdriver.Chrome()

# 打开一个网页
driver.get("https://www.example.com")

# 保存屏幕截图为指定文件名
driver.save_screenshot("screenshot.png")

# 获取屏幕截图的base64编码字符串
screenshot_base64 = driver.get_screenshot_as_base64()

# 获取屏幕截图并保存为指定路径的文件
driver.get_screenshot_as_file("screenshot_path/screenshot.png")

# 获取屏幕截图的二进制文件数据
screenshot_png = driver.get_screenshot_as_png()

# 关闭webdriver实例
driver.quit()

操作思路

首先,我们需要导入相关的库和模块:

python 复制代码
import os
from selenium import webdriver
from time import sleep, strftime, localtime, time
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By

接下来,我们创建一个名为TestCase的类,用于封装测试用例。在__init__方法中,我们初始化Chrome浏览器驱动,并最大化浏览器窗口,然后打开百度首页。

python 复制代码
class TestCase(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://www.baidu.com/')

test1方法中,我们在搜索框中输入关键词"selenium",点击搜索按钮,等待2秒后,使用save_screenshot方法将屏幕截图保存为baidu.png

python 复制代码
def test1(self):
    self.driver.find_element(By.ID,'kw').send_keys('selenium')
    self.driver.find_element(By.ID,'su').click()
    sleep(2)
    self.driver.save_screenshot('baidu.png')

test2方法中,我们在搜索框中输入关键词"selenium",点击搜索按钮,等待2秒后,使用get_screenshot_as_pngget_screenshot_as_base64方法分别获取屏幕截图的二进制数据和base64编码。

python 复制代码
def test2(self):
    self.driver.find_element(By.ID,'kw').send_keys('selenium')
    self.driver.find_element(By.ID,'su').click()
    sleep(2)
    pic = self.driver.get_screenshot_as_png()
    print('pic:',pic)
    pic1 = self.driver.get_screenshot_as_base64()
    print('pic:',pic)
    print('pic1:',pic1)

test3方法中,我们在搜索框中输入关键词"selenium",点击搜索按钮,等待2秒后,使用strftime函数生成截图文件名,然后使用save_screenshot方法将屏幕截图保存为该文件名的png文件。

python 复制代码
def test3(self):
    self.driver.find_element(By.ID,'kw').send_keys('selenium')
    self.driver.find_element(By.ID,'su').click()
    sleep(2)
    st = strftime("%Y-%m-%d-%H-%M-%S",localtime(time()))
    fime_name = st+'.png'
    self.driver.save_screenshot(fime_name)

test4方法中,我们在搜索框中输入关键词"selenium",点击搜索按钮,等待2秒后,使用strftime函数生成截图文件名,然后将屏幕截图保存到与脚本所在目录同级的scrennshot文件夹中。如果该文件夹不存在,则创建该文件夹。

python 复制代码
def test4(self):
    self.driver.find_element(By.ID, 'kw').send_keys('selenium')
    self.driver.find_element(By.ID, 'su').click()
    sleep(2)
    st = strftime("%Y-%m-%d-%H-%M-%S", localtime(time()))
    fime_name = st + '.png'
    current_file_path = os.path.abspath(__file__)
    current_dir = os.path.dirname(current_file_path)
    parent_dir = os.path.dirname(current_dir)
    screenshot_dir = os.path.join(parent_dir, 'scrennshot')
    if not os.path.exists(screenshot_dir):
        os.makedirs(screenshot_dir)
    file_path = os.path.join(screenshot_dir, fime_name)
    self.driver.get_screenshot_as_file(file_path)

最后,在主函数中,我们创建一个TestCase对象,并调用test4方法执行测试用例。

python 复制代码
if __name__ == '__main__':
    case = TestCase()
    case.test4()

完整代码:

python 复制代码
import os
from selenium import webdriver
from time import sleep, strftime, localtime, time
from selenium.webdriver import ActionChains, Keys
from selenium.webdriver.common.by import By

class TestCase(object):
    def __init__(self):
        # 初始化Chrome浏览器驱动
        self.driver = webdriver.Chrome()
        # 最大化浏览器窗口
        self.driver.maximize_window()
        # 打开百度首页
        self.driver.get('https://www.baidu.com/')

    def test1(self):
        # 在搜索框中输入关键词 "selenium"
        self.driver.find_element(By.ID,'kw').send_keys('selenium')
        # 点击搜索按钮
        self.driver.find_element(By.ID,'su').click()
        # 等待2秒
        sleep(2)
        # 保存截图为baidu.png
        self.driver.save_screenshot('baidu.png')

    def test2(self):
        # 在搜索框中输入关键词 "selenium"
        self.driver.find_element(By.ID,'kw').send_keys('selenium')
        # 点击搜索按钮
        self.driver.find_element(By.ID,'su').click()
        # 等待2秒
        sleep(2)
        # 获取截图的二进制数据
        pic = self.driver.get_screenshot_as_png()
        print('pic:',pic)
        # 获取截图的base64编码
        pic1 = self.driver.get_screenshot_as_base64()
        print('pic:',pic)
        print('pic1:',pic1)

    def test3(self):
        # 在搜索框中输入关键词 "selenium"
        self.driver.find_element(By.ID,'kw').send_keys('selenium')
        # 点击搜索按钮
        self.driver.find_element(By.ID,'su').click()
        # 等待2秒
        sleep(2)
        # 生成截图文件名
        st = strftime("%Y-%m-%d-%H-%M-%S",localtime(time()))
        fime_name = st+'.png'
        # 保存截图
        self.driver.save_screenshot(fime_name)

    def test4(self):
        # 在搜索框中输入关键词 "selenium"
        self.driver.find_element(By.ID, 'kw').send_keys('selenium')
        # 点击搜索按钮
        self.driver.find_element(By.ID, 'su').click()
        # 等待2秒
        sleep(2)
        # 生成截图文件名
        st = strftime("%Y-%m-%d-%H-%M-%S", localtime(time()))
        fime_name = st + '.png'
        # 获取当前文件路径
        current_file_path = os.path.abspath(__file__)
        # 获取当前文件所在目录
        current_dir = os.path.dirname(current_file_path)
        # 获取当前文件所在目录的上一级目录
        parent_dir = os.path.dirname(current_dir)
        # 拼接截图保存目录
        screenshot_dir = os.path.join(parent_dir, 'scrennshot')
        # 如果截图保存目录不存在,则创建该目录
        if not os.path.exists(screenshot_dir):
            os.makedirs(screenshot_dir)
        # 拼接截图文件完整路径
        file_path = os.path.join(screenshot_dir, fime_name)
        # 保存截图到指定路径
        self.driver.get_screenshot_as_file(file_path)

if __name__ == '__main__':
    case = TestCase()
    # case.test1()
    # case.test2()
    # case.test3()
    case.test4()

通过以上代码,我们可以实现Selenium屏幕截图功能,并按照日期时间格式保存图片。这样,我们就可以在自动化测试过程中轻松地对测试结果进行截图保存,以便后续的分析和报告。

相关推荐
泛联新安40 分钟前
如何根据项目需求选择合适的软件测试工具?iUnit智能单元测试平台提供专业化解决方案
c++·测试工具·单元测试
Source.Liu4 小时前
【Python自动化】 21.2 Pandas 读取 Excel 时的 dtype 参数完全指南
python·自动化·pandas
Source.Liu8 小时前
【Python自动化】 21.1 Pandas 读取 Excel 文件的完整指南
python·自动化·pandas
幂简集成8 小时前
基于 Gemini 的 CI/CD 自动化测评 API 集成实战教程
运维·ci/cd·自动化
W-GEO9 小时前
Spring Boot 源码深度解析:揭秘自动化配置的魔法
spring boot·后端·自动化
维尔切1 天前
自动化运维-ansible中对于大项目的管理
运维·自动化·ansible
半梦半醒*1 天前
ansible阶段练习题
linux·运维·自动化·ansible·负载均衡·运维开发
c萱1 天前
软件测试错题笔记
软件测试·数据库·笔记·测试工具·oracle·测试用例
双翌视觉1 天前
智能相机还是视觉系统?一文讲透工业视觉两大选择的取舍之道
科技·数码相机·自动化·机器视觉
熊猫钓鱼>_>1 天前
基于腾讯云MCP广场服务Firecrawl MCP网络采集服务构建自动化竞品监测工作日志
自动化·云计算·腾讯云