uiautomator2教程
一、简介
uiautomator2 是一个 Python 库,用于 Android 的 UI 自动化测试,底层基于 Google uiautomator。
二、安装
1、安装adb
2、pip install uiautomator2
3、设备安装 atx - agent,python -m uiautomator2 init
4、安装weditor,进行元素定位,pip install weditor, 启动方式python -m weditor
注:weditor加载失败,可以尝试用uiautodev(uiautodev启动失败,重装uiautomator库后再尝试)
pip install -U uiautodev -i https://pypi.doubanio.com/simple
uiauto.dev
# or: python -m uiautodev
5、安装scrcpy, 可以在电脑上实时看手机的画面,
下载后再环境变量中进行配置Releases · Genymobile/scrcpy · GitHub
启动命令:scrcpy
三、使用教程
1、启动/停止app
import time
import uiautomator2 as u2
device = u2.connect('2f5ce48c')
# 退出app
device.app_stop(package_name="com.xiaomi.smarthome")
time.sleep(1)
# 启动app
device.app_start(package_name="com.xiaomi.smarthome", activity=".SmartHomeMainActivity")
2、查找元素的方法
# -------------------------------------- 查找元素 ---------------------------------------
# 找到的元素返回的是list,默认对第0个元素进行操作,
# 根据文本定位
device(text='路由器').click()
# 根据content-desc 定位
res = device(description="添加设备").click()
# 根据resource-id 定位
device(resourceId="com.xiaomi.smarthome:id/gx").click()
# 根据classname进行定位
device(className='android.widget.TextView')
# 根据包含的文本进行模糊定位
device(textContains="test")
# 根据xpath 进行定位
device.xpath("//android.widget.TextView[@text='M30_test']")
3、获取元素的属性
# -------------------------- 获取元素的属性 ----------------------------
# 判断元素是否存在
print(device(textContains='test').exists)
# 获取文本
print(device(textContains='test').get_text())
4、对元素的操作
# ------------------------- 对元素的操作 ----------------------
#
# 点击
device(text='M30_test').click()
# 长按
device(text='M30_test').long_click()
# 输入文本
device(text="请输入设备名称").click()
time.sleep(1)
device(text="请输入设备名称").send_keys('1666')
5、滑动屏幕
width, height = device.window_size()
# 向上滑动
device.swipe(width / 2, height * 4 / 5, width / 2, height * 2 / 5)
time.sleep(2)
#向下滑动
device.swipe(width / 2, height * 2 / 5, width / 2, height * 4 / 5)
# 向左滑动
device.swipe(width * 4 / 5, height / 3, width * 2 / 5, height / 3)
time.sleep(2)
# 向右滑动
device.swipe(width * 2 / 5, height / 3, width * 4 / 5, height / 3)