关于playwright python

如何实现上一次截图和当前截图对比,有什么好的办法。仅限于playwright python

实现上一次截图和当前截图对比,可以使用 Playwright Python 的 screenshot 方法进行截图,并使用 Pillow 库的 ImageChops 模块进行图片对比。下面是一个示例代码:

import os
from PIL import Image, ImageChops
from playwright.sync_api import Playwright, Browser, Context

def compare_screenshots(filename1: str, filename2: str) -> float:
    # 打开两张图片并转换为灰度图像
    img1 = Image.open(filename1).convert('L')
    img2 = Image.open(filename2).convert('L')
    
    # 计算两张图片的差异值
    diff = ImageChops.difference(img1, img2)
    
    # 统计差异像素点的数量
    histogram = diff.histogram()
    pixels = sum(histogram)
    
    # 计算差异百分比
    percentage = (pixels / float(img1.size[0] * img1.size[1])) * 100
    return percentage

# 创建或连接到浏览器
with Playwright() as p:
    browser = p.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()

    # 导航到目标网站并进行截图比较
    page.goto('https://www.example.com/')
    page.screenshot(path='screenshot-1.png')
    if os.path.exists('screenshot-2.png'):
        percentage = compare_screenshots('screenshot-1.png', 'screenshot-2.png')
        print(f'两张截图的差异百分比为:{percentage:.2f}%')
    else:
        print('未找到历史截图')

    # 保存当前截图并关闭浏览器
    page.screenshot(path='screenshot-2.png')
    context.close()
    browser.close()

上述代码通过 ImageChops.difference() 方法计算两张图片的差异值,并使用像素数量计算差异百分比。如果你需要更详细的截图对比功能,可以使用开源的比较工具如 OpenCV 或 skimage。