本文翻译自https://github.com/openatx/uiautomator2,仅用于个人学习积累记录
uiautomator2建立在ADB工具之上,使用uiautomator2之前必须安装ADB工具,详见ADB命令基本使用
uiautomator2库基础使用教程
一、简介
uiautomator2基于UiAutomator库,UiAutomator是Google提供的用来做安卓自动化测试的一个Java库,基于Accessibility服务。功能很强,可以对第三方App进行测试,获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作,但有两个缺点:1.测试脚本只能使用Java语言2. 测试脚本要打包成jar或者apk包上传到设备上才能运行。
uiautomator2可以实现用python脚本控制测试且可以实现在电脑运行时控制手机。
二、工作原理
python-uiautomator2主要工作原理和ADB命令类似,其也是通过封装ADB命令来实现对Android设备的控制
如上图所示,python-uiautomator2主要分为两部分,python客户端(主机),移动设备(Android设备或虚拟机)
- python脚本:运行脚本并向移动设备发送HTTP请求。
- 移动设备:移动设备上运行了封装了uiautomator2的HTTP服务,解析收到的请求,并转化成uiautomator2的代码。
整个过程
- 在移动设备上安装atx-agent(守护进程),随后atx-agent启动uiautomator2服务(默认7912端口)进行监听
- 在PC上编写测试脚本并执行(相当于发送HTTP请求到移动设备的server端)
- 移动设备通过WIFI或USB接收到PC上发来的HTTP请求,执行制定的操作
三、安装
3.1 需求:
- Android版本 4.4+
- Python 3.6+ (社区反馈3.8.0不支持, 但是3.8.2支持)
3.2 安装adb
使用python的uiautomator2库前必须安装adb工具,uiautomator2可以看作一个对adb工具的封装
3.3 快速开始uiautomator2
- 首先准备一台开启了开发者选项的Android设备,连接电脑,确保执行
adb devices
可以查看到相应的设备 - 运行
pip3 install -U uiautomator2
安装uiautomator2 - 运行
python3 -m uiautomator2 init
安装包含httprpc服务的apk到手机+atx-agent, minicap, minitouch
(值得说明,在旧版的uiautomator2中必须运行这一步,而在1.3.0之后的版本,当运行python代码u2.connect()时就会自动推送这些文件了) - 运行下面代码:
import uiautomator2 as u2 d = u2.connect() # connect to device print(d.info)
- 可以看到下面类似的输出即证明我们可以正常使用这个库了。但是在安装uiautomator2库后我们还需要安装其他的支持库(因版本而异),可以通过具体的报错原因去安装相应的库
{'currentPackageName': 'net.oneplus.launcher', 'displayHeight': 1920, 'displayRotation': 0, 'displaySizeDpX': 411, 'displaySizeDpY': 731, 'displayWidth': 1080, 'productName': 'OnePlus5', ' screenOn': True, 'sdkInt': 27, 'naturalOrientation': True}
3.4 安装weditor
weditor的安装可以方便我们实时查看相应的信息,辅助我们编写脚本,重要的是weditor可以查看相应组件、控件的信息且可以在线进行调试代码
pip3 install -U weditor //uiautomator2, facebook-wda会被作为依赖一并安装上去
安装好之后我们可以运行weditor --help
确认是否安装成功。
具体使用方法如下:
weditor # 启动server并打开浏览器
创建桌面快捷方式(仅限Windows)
weditor --shortcut
更多选项通过 weditor --help
查看
如果浏览器没有自动打开,可以手动访问 http://localhost:17310
github地址为:https://github.com/alibaba/web-editor
3.5 应用即操作
3.5.1 设备连接方法
python-uiautomator2连接手机的方式有两种,一种是通过WIFI,另外一种是通过USB。两种方法各有优缺点。
WIFI最便利的地方就是可以不用连接数据线,USB则可以用在PC和手机网络不在一个网段用不了的情况。
(1)通过WiFi,假设设备IP 192.168.0.1和您的PC在同一网络中
import uiautomator2 as u2
d = u2.connect('192.168.0.1') //WIFI链接设备。或者u2.connect_wifi('10.0.0.1')
(2)通过USB, 假设设备序列是123456789F(见adb devices)
import uiautomator2 as u2
d = u2.connect('123456789F') //USB链接设备。或者u2.connect_usb('123456f')
//d = u2.connect_usb() //当前只有一个设备时可以用这个
在没有参数的情况下调用u2.connect(), uiautomator2将从环境变量ANDROID_DEVICE_IP获取设备IP。如果这个环境变量是空的,uiautomator将返回connect_usb,您需要确保只有一个设备连接到计算机。
3.5.2 检查并维持设备端守护进程处于运行状态
d.healthcheck()
3.5.3 打开调试开关
d.debug = True
d.info
'''
返回
12:32:47.182 $ curl -X POST -d '{"jsonrpc": "2.0", "id": "b80d3a488580be1f3e9cb3e926175310", "method": "deviceInfo", "params": {}}' 'http://127.0.0.1:54179/jsonrpc/0'
12:32:47.225 Response >>>
{"jsonrpc":"2.0","id":"b80d3a488580be1f3e9cb3e926175310","result":{"currentPackageName":"com.android.mms","displayHeight":1920,"displayRotation":0,"displaySizeDpX":360,"displaySizeDpY":640,"displayWidth":1080,"productName"
:"odin","screenOn":true,"sdkInt":25,"naturalOrientation":true}}
3.5.4 安装应用
只能通过URL安装
d.app_install('http://some-domain.com/some.apk') //引号内为下载apk地址
3.5.5 启动以及停止应用
#启动软件
d.app_start('包名', '界面名') //或者d.app_start('包名')
#停止应用
//相当于'am force-stop'强制停止应用
d.app_stop('com.example.hello_world') //引号内为包名称
//相当于'pm clear' 清空App数据
d.app_clear('com.example.hello_world')
#停止所有正在运行的应用程序
d.app_stop_all()
//停止所有应用程序,除了com.examples.demo
d.app_stop_all(excludes=['com.examples.demo'])
3.5.6 停止和跳过弹窗
d.disable_popups() #自动跳过弹出窗口
d.disable_popups(False) #禁用自动跳过弹出窗口
3.5.7 Session
Session表示应用程序的生命周期。可用于启动应用,检测应用崩溃
- 启动和关闭应用程序
sess = d.session("com.netease.cloudmusic") # start 网易云音乐
sess.close() # 停止网易云音乐
- 使用python with启动和关闭应用程序
with d.session("com.netease.cloudmusic") as sess:
sess(text="Play").click()
- 链接正在运行的应用
# launch app if not running, skip launch if already running
sess = d.session("com.netease.cloudmusic", attach=True)
# raise SessionBrokenError if not running
sess = d.session("com.netease.cloudmusic", attach=True, strict=True)
- 检测应用崩溃
# App正在运行时
sess(text="Music").click() # 操作是正常的
# App崩溃时
sess(text="Music").click() # 引发会话中断错误SessionBrokenError
# session下的其他函数调用也会引发SessionBrokenError错误
# 检查会话是否正确。
# 警告:函数名将来可能会更改
sess.running() # True or False
3.5.8 获取设备信息
- 获取设备信息
d.info
// 以下是可能输出结果:
{
u'displayRotation': 0,
u'displaySizeDpY': 640,
u'displaySizeDpX': 360,
u'currentPackageName': u'com.android.launcher',
u'productName': u'takju',
u'displayWidth': 720,
u'sdkInt': 18,
u'displayHeight': 1184,
u'naturalOrientation': True
}
- 获取窗口大小
d.window_size()
//设备垂直输出示例: (1080, 1920)
//设备水平输出示例: (1920, 1080)
- 获取当前应用程序信息
d.current_app()
//输出示例 1: {'package': 'com.netease.example', 'activity': '.Client', 'pid': 23710}
//输出示例 2: {'package': 'com.ruguoapp.jike', 'activity': 'com.ruguoapp.jike.business.video.ui.activity.videolist.VideoListActivity'}
- 获取设备序列号
d.serial
//输出示例: 74aAEDR428Z9
- 获取WIFI IP
print(d.wlan_ip)
//输出示例:10.0.0.1
- 获取详细的设备信息
print(d.device_info)
//输出示例:
{'udid': '3578298f-b4:0b:44:e6:1f:90-OD103',
'version': '7.1.1',
'serial': '3578298f',
'brand': 'SMARTISAN',
'model': 'OD103',
'hwaddr': 'b4:0b:44:e6:1f:90',
'port': 7912,
'sdk': 25,
'agentVersion': 'dev',
'display': {'width': 1080, 'height': 1920},
'battery': {'acPowered': False,
'usbPowered': False,
'wirelessPowered': False,
'status': 3,
'health': 0,
'present': True,
'level': 99,
'scale': 100,
'voltage': 4316,
'temperature': 272,
'technology': 'Li-ion'},
'memory': {'total': 3690280, 'around': '4 GB'},
'cpu': {'cores': 8, 'hardware': 'Qualcomm Technologies, Inc MSM8953Pro'},
'presenceChangedAt': '0001-01-01T00:00:00Z',
'usingBeganAt': '0001-01-01T00:00:00Z'}
3.5.9 获取应用信息
d.app_info("com.examples.demo")
# 会输出
#{
# "mainActivity": "com.github.uiautomator.MainActivity",
# "label": "ATX",
# "versionName": "1.1.7",
# "versionCode": 1001007,
# "size":1760809
#}
# 保存应用程序图标
img = d.app_icon("com.examples.demo")
img.save("icon.png")
3.5.10 推拉文件
- 将文件推送到设备
//push文件夹
d.push("foo.txt", "/sdcard/")
//push和重命名
d.push("foo.txt", "/sdcard/bar.txt")
//push fileobj
with open("foo.txt", 'rb') as f:
d.push(f, "/sdcard/")
//推动和更改文件访问模式
d.push("foo.sh", "/data/local/tmp/", mode=0o755)
- 从设备中拉出一个文件
d.pull("/sdcard/tmp.txt", "tmp.txt")
//如果在设备上找不到文件,FileNotFoundError将引发
d.pull("/sdcard/some-file-not-exists.txt", "tmp.txt")
3.5.11 关键事件
d.screen_on() //打开屏幕
d.screen_off() //关闭屏幕
d.info.get(' screenOn ') //获取当前屏幕状态,需要 Android >= 4.4
d.unlock() //解锁屏幕
- 键盘操作以及软键盘操作
d.press("home") # 点击home键
d.press("back") # 点击back键
d.press("left") # 点击左键
d.press("right") # 点击右键
d.press("up") # 点击上键
d.press("down") # 点击下键
d.press("center") # 点击选中
d.press("menu") # 点击menu按键
d.press("search") # 点击搜索按键
d.press("enter") # 点击enter键
d.press("delete") # 点击删除按键
d.press("recent") # 点击近期活动按键
d.press("volume_up") # 音量+
d.press("volume_down") # 音量-
d.press("volume_mute") # 静音
d.press("camera") # 相机
d.press("power") #电源键
3.5.12 手势交互
# 1、单击屏幕
d.click(x,y) # x,y为点击坐标
# 2、双击屏幕
d.double_click(x,y)
d.double_click(x,y,0.1) # 默认两个单击之间间隔时间为0.1秒
# 3、长按
d.long_click(x,y)
d.long_click(x,y,0.5) # 长按0.5秒(默认)
# 4、滑动
d.swipe(sx, sy, ex, ey)
d.swipe(sx, sy, ex, ey, 0.5) #滑动0.5s(default)
# 5、拖动
d.drag(sx, sy, ex, ey)
d.drag(sx, sy, ex, ey, 0.5)#拖动0.5s(default)
# 6、滑动点 多用于九宫格解锁,提前获取到每个点的相对坐标(这里支持百分比)
# 从点(x0, y0)滑到点(x1, y1)再滑到点(x2, y2)
# 两点之间的滑动速度是0.2秒
d.swipe((x0, y0), (x1, y1), (x2, y2), 0.2)
# 注意:单击,滑动,拖动操作支持百分比位置值。例:
d.long_click(0.5, 0.5) # 表示长按屏幕中心
补充:
SwipeExt 扩展功能
#SwipeExt 扩展功能
d.swipe_ext("right") # 手指右滑,4选1 "left", "right", "up", "down"
d.swipe_ext("right", scale=0.9) # 默认0.9, 滑动距离为屏幕宽度的90%
d.swipe_ext("right", box=(0, 0, 100, 100)) # 在 (0,0) -> (100, 100) 这个区域做滑动
# 实践发现上滑或下滑的时候,从中点开始滑动成功率会高一些
d.swipe_ext("up", scale=0.8) # 代码会vkk
# 还可以使用Direction作为参数
from uiautomator2 import Direction
d.swipe_ext(Direction.FORWARD) # 页面下翻, 等价于 d.swipe_ext("up"), 只是更好理解
d.swipe_ext(Direction.BACKWARD) # 页面上翻
d.swipe_ext(Direction.HORIZ_FORWARD) # 页面水平右翻
d.swipe_ext(Direction.HORIZ_BACKWARD) # 页面水平左翻
Drag:
d.drag(sx, sy, ex, ey)
d.drag(sx, sy, ex, ey, 0.5) # swipe for 0.5s(default)
Swipe points
# swipe from point(x0, y0) to point(x1, y1) then to point(x2, y2)
# time will speed 0.2s bwtween two points
d.swipe_points([(x0, y0), (x1, y1), (x2, y2)], 0.2))
3.5.13 屏幕相关
# 1、检索方向
d.orientation
# 检索方向。输出可以是 "natural" or "left" or "right" or "upsidedown"
# 2、设置方向
d.set_orientation('l') # or "left"
d.set_orientation("l") # or "left"
d.set_orientation("r") # or "right"
d.set_orientation("n") # or "natural"
# 3、冻结/开启旋转
d.freeze_rotation()# 冻结旋转
d.freeze_rotation(False)# 开启旋转
# 4、转储UI层次结构
# get the UI hierarchy dump content (unicoded).(获取UI层次结构转储内容)
d.dump_hierarchy()
# 5、打开通知或快速设置
d.open_notification()#下拉打开通知栏
d.open_quick_settings()#下拉打开快速设置栏
- 截屏
# 截图并保存到电脑上的一个文件中,需要Android>=4.2。
d.screenshot("home.jpg")
# 得到PIL.Image格式的图像. 但你必须先安装pillow
image = d.screenshot() # default format="pillow"
image.save("home.jpg") # 或'home.png',目前只支持png 和 jpg格式的图像
# 得到OpenCV的格式图像。当然,你需要numpy和cv2安装第一个
import cv2
image = d.screenshot(format='opencv')
cv2.imwrite('home.jpg', image)
# 获取原始JPEG数据
imagebin = d.screenshot(format='raw')
open("some.jpg", "wb").write(imagebin)
3.5.14 UI的定位方式
UI定位即选择器机制,选择器机制是一种方便的机制,用于在当前的窗口中标识特定的UI对象。
支持方法很多,这里不一一赘述,具体可以去看https://github.com/openatx/uiautomator2
下面我们主要说一下Xpath定位方法
3.5.15 Xpath
uiautomator2的Xpath方法最根本的就是定位到一个组件的位置然后对相应位置进行.click()
动作(坐标是强制点击,在范围内时一定会点击成功)
例如:下面是一个节点的内容:
常见用法:
# 等待10s
d.xpath("//android.widget.TextView").wait(10.0)
# 找到并单击
d.xpath("//*[@content-desc='分享']").click()
# 检查是否存在
if d.xpath("//android.widget.TextView[contains(@text, 'Se')]").exists:
print("exists")
# 获取所有文本视图文本、属性和中心点
for elem in d.xpath("//android.widget.TextView").all():
print("Text:", elem.text)
#获取视图文本
for elem in d.xpath("//android.widget.TextView").all():
print("Attrib:", elem.attrib)
# 获取属性和中心点
# 返回: (100, 200)
for elem in d.xpath("//android.widget.TextView").all():
print("Position:", elem.center())
# 所有元素
//*
# resource-id包含login字符
//*[contains(@resource-id, 'login')]
# 按钮包含账号或帐号
//android.widget.Button[contains(@text, '账号') or contains(@text, '帐号')]
# 所有ImageView中的第二个
(//android.widget.ImageView)[2]
# 所有ImageView中的最后一个
(//android.widget.ImageView)[last()]
# className包含ImageView
//*[contains(name(), "ImageView")]
具体可见-XPah使用详解
四、应用实例
import uiautomator2 as u2
import time
import xml.etree.ElementTree as ET
class U2(object):
def __init__(self, deviceID = ""):
self.deviceID = deviceID
self.d = self.connectPhone(self.deviceID)
def connectPhone(self, devices=""):
if devices == None:
d = u2.connect_usb() # 只有一个设备连接使用
else:
d = u2.connect(devices)
return d
def openPhone(self):
self.d.screen_on() # 打开屏幕
self.d.unlock() # 解锁手机
self.d.swipe(324, 2068, 324, 500)
def startApp(self,packageName = ""):
if packageName == "":
print("请输入APP包名")
else:
self.packageName = packageName
self.d.app_start(packageName, stop=True) # 打开相应的福特派软件
time.sleep(20)
pid = self.d.app_wait(packageName) # 等待应用运行, return pid(int)
if not pid:
print("com.example.android is not running")
else:
print("com.example.android pid is %d" % pid)
def __findNode(self,strxml, faceName):
index = strxml.index(faceName)
substring = strxml[:index + 1]
substring1 = strxml[index:]
nodeStart = substring.rfind("<")
nodeEnd = substring1.find(">") + index
# 获得相应的节点
nodelist = strxml[nodeStart:nodeEnd + 1]
# 将字符串类型的节点转换为节点字典
root = ET.fromstring(nodelist)
attributes = root.attrib
return attributes
def openMainFace(self, faceName = ""):
if faceName == "":
pass
else:
xml = self.d.dump_hierarchy() # str类型
nodeDict = self.__findNode(xml, faceName)
value = nodeDict['content-desc']
Xpath_face = '//*[@content-desc="{}"]'.format(value)
x, y = self.d.xpath(Xpath_face).center()
self.d.click(x, y)
def clickButton(self,buttonName, islongclick: bool = True, longclickTime: float = .5):
# 默认是长按0.5秒
xml = self.d.dump_hierarchy() # str类型
nodeDict = self.__findNode(xml, buttonName)
value = nodeDict['content-desc']
Xpath_face = '//*[@content-desc="{}"]'.format(value)
x, y = self.d.xpath(Xpath_face).center()
if islongclick:
if longclickTime == 0:
self.d.long_click(x, y)
else:
self.d.long_click(x, y, longclickTime)
else:
self.d.click(x, y)
def stopApp(self):
self.d.app_stop(self.packageName)
def closePhone(self):
self.d.screen_off()
五、Google uiautomator与py uiautomator2的区别
- API相似但是不完全兼容
- uiautomator2是安卓项目,而uiautomator是Java项目
- uiautomator2可以输入中文,而uiautomator的Java工程需借助utf7输入法才能输入中文
- uiautomator2必须明确EditText框才能向里面输入文字,uiautomator直接指定父类也可以在子类中输入文字
- uiautomator2获取控件速度比uiautomator快