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

相关推荐
像风一样自由20201 小时前
浏览器自动化工具:Selenium 和 Playwright
运维·selenium·自动化
xaletry8881 小时前
环境-疲劳载荷综合试验系统
测试工具
引量AI4 小时前
TikTok 矩阵 AI 自动化运营:解锁短视频流量密码
人工智能·矩阵·自动化·tiktok矩阵·海外社媒
大道归简4 小时前
0. Selenium工具的安装
selenium·测试工具
hi星尘11 小时前
深度解析:基于Python的微信小程序自动化操作实现
python·微信小程序·自动化
Hy行者勇哥12 小时前
用Postman验证IAM Token的实际操作
测试工具·postman
cxr82813 小时前
基于Playwright的浏览器自动化MCP服务
人工智能·自动化·大语言模型·mcp
群联云防护小杜13 小时前
云服务器主动防御策略与自动化防护(下)
运维·服务器·分布式·安全·自动化·音视频
PPIO派欧云13 小时前
PPIO X OWL:一键开启任务自动化的高效革命
运维·人工智能·自动化·github·api·教程·ppio派欧云
struggle202514 小时前
LinuxAgent开源程序是一款智能运维助手,通过接入 DeepSeek API 实现对 Linux 终端的自然语言控制,帮助用户更高效地进行系统运维工作
linux·运维·服务器·人工智能·自动化·deepseek