在appium中,如何通过匹配图片来进行断言?

在Appium中进行图片匹配断言,可以使用OpenCV来实现。以下是使用Appium和OpenCV进行图片匹配断言的示例代码。

首先,需要确保安装了必要的库:

bash 复制代码
pip install opencv-python-headless
pip install opencv-python
pip install numpy

然后,下面是一个示例代码,展示如何使用Appium和OpenCV进行图片匹配断言:

python 复制代码
import cv2
import numpy as np
from appium import webdriver

# 配置Appium服务器和设备
desired_caps = {
    'platformName': 'Android',
    'platformVersion': '10',
    'deviceName': 'Android Emulator',
    'app': '<path_to_your_app>',
    'automationName': 'UiAutomator2',
}

# 启动Appium客户端
driver = webdriver.Remote('<http://localhost:4723/wd/hub>', desired_caps)

def load_image(image_path):
    """
    加载图片并转换为灰度图像
    """
    image = cv2.imread(image_path, 0)
    if image is None:
        raise FileNotFoundError(f"Image file '{image_path}' not found.")
    return image

def find_image_in_screenshot(screenshot_path, template_path, threshold=0.8):
    """
    在屏幕截图中查找模板图片
    """
    screenshot = load_image(screenshot_path)
    template = load_image(template_path)

    result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    if max_val >= threshold:
        return True, max_loc
    else:
        return False, None

# 获取屏幕截图
screenshot_path = 'screenshot.png'
driver.save_screenshot(screenshot_path)

# 模板图片路径
template_path = 'template.png'

# 进行图片匹配断言
is_found, location = find_image_in_screenshot(screenshot_path, template_path)

if is_found:
    print(f"Template found at location: {location}")
else:
    print("Template not found in screenshot")

# 关闭Appium客户端
driver.quit()

代码说明

  1. 加载图片load_image函数用于加载并转换图片为灰度图像。
  2. 查找模板图片find_image_in_screenshot函数在屏幕截图中查找模板图片。使用OpenCV的matchTemplate方法进行模板匹配,如果匹配度超过指定的阈值(默认0.8),则返回匹配的位置。
  3. 获取屏幕截图 :通过driver.save_screenshot方法获取当前屏幕截图并保存为文件。
  4. 进行图片匹配断言 :调用find_image_in_screenshot进行图片匹配,并根据结果进行断言。

通过上述代码,可以在Appium测试中使用图片匹配进行断言。请确保模板图片和屏幕截图的分辨率和比例一致,以提高匹配的准确性。

相关推荐
ii_best3 小时前
按键精灵安卓/iOS脚本辅助,OpenCV实现自动化高效率工具
ios·自动化·编辑器·安卓
守城小轩6 小时前
基于Chrome140的TK账号自动化——脚本撰写(二)
自动化·浏览器自动化·tk自动化·rpa自动化·tk养号
熊猫钓鱼>_>6 小时前
基于模板提高垂直领域大模型应用场景的文字语言组织准确性
自动化·llm·多模态·模板·rag·垂直领域
minhuan11 小时前
构建AI智能体:七十五、用扣子平台创建工作流:从自动化到智能化的进阶之路
运维·自动化·工作流构建·意图识别工作流
GJGCY18 小时前
金融智能体的技术底座解析:AI Agent如何实现“认知+执行”闭环?
人工智能·经验分享·ai·金融·自动化
小安运维日记1 天前
RHCA - DO374 | Day03:通过自动化控制器运行剧本
linux·运维·数据库·自动化·ansible·1024程序员节
darkfive1 天前
构建大模型安全自动化测试框架:从手工POC到AI对抗AI的递归Fuzz实践
人工智能·安全·ai·自动化
程序员小远1 天前
使用Jmeter进行http接口测试
自动化测试·软件测试·python·测试工具·jmeter·http·接口测试
yubo05091 天前
自动化模型学习器——autoGluon
机器学习·自动化