python-uiautomator2使用记录

本文介绍了使用Python的uiautomator2库进行自动化测试,涵盖了截图、指定区域截图、图片相似度对比、视频录制、Allure报告上传以及UI操作如隐式等待、相对定位、滚动和滑动等技术。同时提到了ADB工具的使用和一些配置注意事项。
摘要由CSDN通过智能技术生成
  • python 安装 uiautomator2 、weditor
  • 电脑安装adb
  • adb 连接设备
    adb connect ip
    adb devices
  • 设备上安装atx-agent
    注意:要设置允许安装的权限,adb shell setenforce 0
    adb shell setenforce 0 //设置成permissive 模式
    adb shell setenforce 1 //设置成enforce 模式
    python -m uiautomator2 init
  • 启动 weditor
    python -m weditor
截图
  • 全屏
import uiautomator2 as u2

d = u2.connect()
d.screenshot()
d.screenshot().save('test.png')

  • 指定区域
import uiautomator2 as u2

d = u2.connect()
d.xpath("").screenshot() # Image.Image
d(text="").screenshot()

  • 图片相似度对比
import imagehash
from PIL import Image

def check_similarity(image: Image.Image, temp_image: Image.Image, similarity=1):
    hash1 = imagehash.average_hash(image)
    hash2 = imagehash.average_hash(temp_image)
    act_similarity = 1 - (hash1 - hash2) / len(hash1.hash) ** 2
    if act_similarity < similarity:
    raise Exception(f"similarity:{act_similarity} less than {similarity}")
    else:
    return Result(status=True, result=act_similarity)
视频录制
import uiautomator2 as u2
import time

d = u2.connect()

d.screenrecord(r'output.mp4')
time.sleep(2)
d.screenrecord.stop()

allure 上传视频

def test_mp4(self):
    content = ""
    with open(r"output.mp4", mode="rb") as f:
    content = f.read()
    allure.attach(content, attachment_type=allure.attachment_type.MP4)

隐式等待

d.implicitly_wait(等待时长) #单位是s
swipe_ext(),不需要坐标,只需提供方向

相对定位

关键词:left,right,top,bottom

d(A).left(B),选择A左侧的B。

d(A).right(B),选择A右侧的B。

d(A).up(B),选择A上方的B。

d(A).down(B),在A下选择B。

滚动

# 垂直滚动到页面顶部/横向滚动到最左侧
d(scrollable=True).scroll.toBeginning()
d(scrollable=True).scroll.horiz.toBeginning()
# 垂直滚动到页面最底部/横向滚动到最右侧
d(scrollable=True).scroll.toEnd()
d(scrollable=True).scroll.horiz.toEnd()
# 垂直向后滚动到指定位置/横向向右滚动到指定位置
d(scrollable=True).scroll.to(description="指定位置")
d(scrollable=True).scroll.horiz.to(description="指定位置")
# 垂直向前滚动(横向同理)
d(scrollable=True).scroll.forward()
# 垂直向前滚动到指定位置(横向同理)
d(scrollable=True).scroll.forward.to(description="指定位置")

滑动

d.swipe(sx, sy, ex, ey)
d.swipe_ext(direction)
# direction
#     LEFT = "left"
#    RIGHT = "right"
#    UP = "up"
#    DOWN = "down"
Ui_Object.swipe(direction)

拖拽

# 从sx,sy坐标拖拽至ex,ey坐标
d.drag(sx, sy, ex, ey)

d.exists(scrollable=True, descriptionContains=“描述内容”)

配置总体延迟, 发现点击延迟配置click_post_delay的语句被弃用了,即后期版本的uiautomator2不再支持

# 配置点击前延时0.5s,点击后延时1s
d.settings[‘operation_delay’] = (.5, 1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值