uiautomator2 简介
UiAutomator是Google提供的用来做安卓自动化测试的一个Java库,基于Accessibility服务。功能很强,可以对第三方App进行测试,获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作。而uiautomator2便是UiAutomator的Python实现
除了对原有的库的bug进行了修复,还增加了很多新的Feature。主要有以下部分:
- 设备和开发机可以脱离数据线,通过WiFi互联(基于atx-agent)
- 集成了openstf/minicap达到实时屏幕投频,以及实时截图
- 集成了openstf/minitouch达到精确实时控制设备
- 修复了xiaocong/uiautomator经常性退出的问题
- 代码进行了重构和精简,方便维护
- 实现了一个设备管理平台(也支持iOS) atxserver2
- 扩充了toast获取和展示的功能
相关链接如下:
UiAutomator:https://developer.android.com/training/testing/ui-automator.html
uiautomator2: https://github.com/openatx/uiautomator2
QUICK_REFERENCE: https://github.com/openatx/uiautomator2/blob/master/QUICK_REFERENCE.md
安装
由于python实现的,在此可以使用pip 直接安装即可,命令如下
1 |
# # 如果是在Windows平台下,未做`python3` 与 `python` 的link,在这里使用`python` 而不是`python3` |
Tips: 建议使用虚拟环境
开发版安装
1 |
python3 -m pip install --upgrade --pre uiautomator2 |
源码安装
需要git客户端,若未安装git,可移步
https://git-scm.com/downloads进行下载,当然,源码也可以使用zip的方式进行下载,请自行探索
1 |
git clone https://github.com/openatx/uiautomator2 |
校验
先准备一台(不要两台)开启了开发者选项的安卓手机,连接上电脑,确保执行adb devices可以看到连接上的设备。如下图所示

运行python3 -m uiautomator2 init安装包含httprpc服务的apk到手机+atx-agent, minicap, minitouch
在过去的版本中,这一步是必须执行的,但是从1.3.0之后的版本,当运行python代码
u2.connect()时就会自动推送这些文件了
1 |
import uiautomator2 as u2 |

app开启与关闭
当我们需要打开对应的app时,需要知道对应设备的包名。获取包名有两种方式
- 在设备上打开对应的app,获取当前app包名(
app_current()) - 获取全部的应用包(
app_list_running())
1 |
# 开启app |
Example
此时笔者的测试手机在已经打开app
1 |
#!/usr/bin/env python3 |
Tips: 复习一下adb command
1 |
# adb 命令 -- 获取报包名 |
点击
-
Turn on/off screen
1
2d.screen_on() # turn on the screen
d.screen_off() # turn off the screen -
Press hard/soft key
1
2
3d.press("home") # press the home key, with key name
d.press("back") # press the back key, with key name
d.press(0x07, 0x02) # press keycode 0x07('0') with META ALT(0x02) -
These key names are currently supported:
-
home、back、
-
left、right、up、down
-
center、menu、search
-
enter、delete ( or del)
-
recent (recent apps)
-
volume_up、volume_down、volume_mute
-
camera、power
-
-
Click on the screen
1 |
d.click(x, y) |
- Double click
1 |
d.double_click(x, y) |
- long_click
1 |
d.long_click(x, y) |
滑动
Swipe
1 |
# Swipe |
swipe_ext
1 |
d.swipe_ext("right") # 手指右滑,4选1 "left", "right", "up", "down" |
Drag
1 |
d.drag(sx, sy, ex, ey) |
Swipe points
1 |
# swipe from point(x0, y0) to point(x1, y1) then to point(x2, y2) |
选择器
选择器是一种在当前窗口中识别特定 UI 对象的便捷机制, 很多时候仅按照坐标时点击并不精确,通用型不强。
选择器支持以下参数。有关详细信息,请参阅UiSelector Java 文档。
text,textContains,textMatches,textStartsWithclassName,classNameMatchesdescription,descriptionContains,descriptionMatches,descriptionStartsWithcheckable,checked,clickable,longClickablescrollable,enabled,focusable,focused,selectedpackageName,packageNameMatchesresourceId,resourceIdMatchesindex,instance