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屏幕截图功能,并按照日期时间格式保存图片。这样,我们就可以在自动化测试过程中轻松地对测试结果进行截图保存,以便后续的分析和报告。

相关推荐
onceco6 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
Small black human9 小时前
HTTP-Postman的安装及其使用
测试工具·postman
galaxylove11 小时前
Gartner发布塑造安全运营未来的关键 AI 自动化趋势
人工智能·安全·自动化
AIZHINAN12 小时前
Appium 简介
自动化测试·测试工具·appium
Oooon_the_way13 小时前
UI自动化-Puppeteer
自动化
宇钶宇夕15 小时前
针对工业触摸屏维修的系统指南和资源获取途径
单片机·嵌入式硬件·自动化
吴free19 小时前
mac电脑wireshark快速实现http接口抓包
网络·测试工具·http·wireshark
真智AI19 小时前
利用 Claude Opus 4 自动化 GitHub 工作流:从安装到实战详解
运维·自动化·github
艾立泰智能包装1 天前
电商分拣的“效率密码”:艾立泰轻量化托盘引领自动化流水线革新
运维·自动化
cpsvps_net1 天前
Windows内存泄漏自动化
运维·自动化