A way to automate screen recording with Selenium

Due to the instability of UI layer automation, it is common to encounter execution interruptions or use case failures. Here are some common measures to take.

  1. detailed log
  2. Screenshot when positioning error
  3. Pytest's caching mechanism (can record which ones succeeded and which ones failed)
  4. Automatic retry mechanism (like pytest-rerunfailures)
  5. Use case video

Use case recording is the most intuitive way to view real-time operations. Many cloud platforms such as Saucelabs provide the function of use case recording.
Unfortunately, however, selenium itself does not have this capability. In addition to using third-party software such as ffmpeg to record the screen synchronously, another implementation method is to start another thread, take screenshots continuously, and finally stitch the pictures into git.
The operation method is as follows.

real-time screenshot

  1. Write a loop screenshot function shot
def shot(dr):
    i = 0
    while True:
        img_file = os.path.join(img_dir, f'{i}.png')
        try:
            dr.save_screenshot(img_file)
        except:
            return
        i += 1

Due to the speed limit of executing the screenshot command on the webdriver interface, there is no need to sleep for each round of screenshot.
2. When operating the web, start a thread

img_dir = 'img'  # 临时图片目录
dr = webdriver.Chrome()

t = threading.Thread(target=shot, args=(dr, img_dir))  # 新建线程
t.start()  # 启动截图线程

dr.get('https://www.baidu.com')
dr.find_element('id', 'kw').send_keys('csdn测试八戒')
dr.find_element('id', 'su').click()
time.sleep(1)
dr.get('https://www.qq.com')
dr.back()
time.sleep(2)
dr.quit()
  1. splicing pictures into gif

Pillow needs to be installed: pip install pillow

img_list = os.listdir(img_dir)  # 列出目录所有图片
img_list.sort(key=lambda x: int(x[:-4]))  # 排序

first_img = Image.open(os.path.join(img_dir, img_list[0]))  # 第一张图片对象
else_imgs = [Image.open(os.path.join(img_dir, img)) for img in img_list[1:]]  # 剩余图片对象

first_img.save("record.gif", append_images=else_imgs,
               duration=300,
               save_all=True) # 拼接保存

full code

from selenium import webdriver
import threading
import os
import time
from PIL import Image


def clear_dir(path):
    """创建或清空目录"""
    if not os.path.isdir(path):
        os.mkdir(path)  # 创建目录
    else:  # 清空目录
        [os.remove(os.path.join(path, file_name)) for file_name in os.listdir(path)]


def shot(dr, img_dir):
    """循环截图函数"""
    i = 0
    clear_dir(img_dir)  # 清空目录
    while True:
        img_file = os.path.join(img_dir, f'{i}.png')
        try:
            dr.save_screenshot(img_file)
        except:
            return
        i += 1


# Selenium操作
img_dir = 'img'  # 临时图片目录
dr = webdriver.Chrome()

t = threading.Thread(target=shot, args=(dr, img_dir))  # 新建线程
t.start()  # 启动截图线程

dr.get('https://www.baidu.com')
dr.find_element('id', 'kw').send_keys('csdn测试八戒')
dr.find_element('id', 'su').click()
time.sleep(1)
dr.get('https://www.qq.com')
dr.back()
time.sleep(2)
dr.quit()

# 图片拼接成gif
img_list = os.listdir(img_dir)  # 列出目录所有图片
img_list.sort(key=lambda x: int(x[:-4]))  # 排序

first_img = Image.open(os.path.join(img_dir, img_list[0]))  # 第一张图片对象
else_imgs = [Image.open(os.path.join(img_dir, img)) for img in img_list[1:]]  # 剩余图片对象

first_img.save("record.gif", append_images=else_imgs,
               duration=300,  # 每张图片的过过渡时间
               save_all=True) # 拼接保存,如果想要循环播放可以加上loop=0

Optical theory is useless, you have to learn to follow along, and you have to do it yourself, so that you can apply what you have learned to practice. At this time, you can learn from some actual combat cases.

If it is helpful to you, please like and collect it to give the author an encouragement. It is also convenient for you to quickly find it next time.

If you don’t understand, please consult the small card below. The blogger also hopes to learn and progress with like-minded testers

At the right age, choose the right position, and try to give full play to your own advantages.

My road of automated test development is inseparable from the plan of each stage along the way, because I like planning and summarizing,

Test and develop video tutorials, study notes and receive portals! ! !

Guess you like

Origin blog.csdn.net/m0_59868866/article/details/130561271