- 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)