Uiautomator2资料文档


语法简介

API 文档一

1.隐式等待

1.隐式等待
import uiautomator2 as u2
serialno = ‘7f3dec60’
d = u2.connect_usb(serialno)
d.implicitly_wait(3.0)

#3秒内未找到“搜索”按钮,则抛出错误uiautomator2.exceptions.UiObjectNotFoundError: -32002 Client error: <> data: , method: None

#此函数会影响以下事件click, long_click, drag_to, get_text, set_text, clear_tex

d(text=“搜索”).click()#找到此按钮则直接点击

2.App启停基本操作

2.App启停基本操作

2.1安装app(仅支持从URL安装apk):d.app_install(‘http://some-domain.com/some.apk’)
卸载app:d.app_uninstall(pk_name)

2.2启动app:d.app_start(package_name)

2.3停止app:d.app_stop(package_name) #等同于am force-stop强制停止app,可能会丢失数据
d.app_clear(package_name)#等同于pm clear

2.4停止所有app:d.app_stop_all(excludes=[package_name])#停止所有app除了括号内的,括号内容可选

2.5获取app信息:d.app_info(package_name)
保存app icon:img=d.app_icon(pkname)
img.save(“icon.png”)

3.文件推送/拉取

3.文件推送/拉取

3.1推送文件到设备中:d.push(“foo.txt”, “/sdcard/”)

3.2推送文件并重命名:d.push(“foo.txt”, “/sdcard/bar.txt”)

3.3推送文件对象:with open(“foo.txt”, ‘rb’) as f:
d.push(f, “/sdcard/”)

3.4推送并改变文件访问权限:d.push(“foo.sh”, “/data/local/tmp/”, mode=0o755)

3.5从设备中拉取文件到本地:d.pull(“/sdcard/tmp.txt”, “tmp.txt”)

3.6从设备中拉取的文件不存在时 抛出错误:FileNotFoundError:d.pull(“/sdcard/some-file-not-exists.txt”, “tmp.txt”)

这里顺便说下快速获取apk相关包名信息的一些简易方法

a.获取包名:d.app_stop_all(),会列出一个当前打开的所有app的包名列表;
print(d.current_app()) 打印当前运行的app信息

b.命令行打印安装的所有包:adb shell pm list packages -3

c.打印安装包路径:adb shell pm path “包名”

d.打印安装包信息:aapt d badging “apk包路径”

4.自动点击权限对话框

4.自动点击权限对话框

官方说:disable_popups函数,检测发现很不稳定,暂时不要使用--一会儿试试看

d.disable_popups() #自动跳过弹出框
d.disable_popups(False) # 禁用自动跳过

如果此方法无法在你的设备上运行,可以按如下步骤操作获取控件

4.1打开Open uiautomatorviewer.bat

4.2获取弹出框hierarchy

5.执行shell命令

5.执行shell命令

shell命令:d.adb_shell(‘pwd’)
output, exit_code = d.shell(“pwd”, timeout=60) # timeout 60s (Default)
#output: “/\n”, exit_code: 0
#Similar to command: adb shell pwd

#Since shell function return type is namedtuple(“ShellResponse”, (“output”, “exit_code”))
#so we can do some tricks
output = d.shell(“pwd”).output
exit_code = d.shell(“pwd”).exit_code
The first argument can be list. for example

output, exit_code = d.shell([“ls”, “-l”])
#output: “/…”, exit_code: 0

6.通过会话操作app

6.通过会话操作app

启动微信:sess=d.session(“com.tencent.mm”)
停止微信:sess.close()

使用python操作app,打开微信→点击腾讯新闻→关闭app

with d.session(“com.tencent.mm”) as sess:
  sess(text=“腾讯新闻”).click()

添加app到正在运行状态:sess=d.session(“包名”,attach=True)

检查app运行状态:sess.running() #返回True或False

7.获得设备基本信息

7.获得设备基本信息

设备概要信息:d.info
设备详细信息:d.device_info
设备窗口尺寸:d.window_size()
当前运行app信息:d.current_app()
设备序列号:d.serial
设备Wlanip:d.wlan_ip
等待Activity:d.wait_activity(“com.tencent.mm.ui.LauncherUI”,timeout=5)#若不设置默认超时10秒,返回True or False

API 文档二

1.设备屏幕事件

1.设备屏幕事件

熄灭屏幕d.screen_off()
唤醒屏幕d.screen_on()
屏蔽状态d.info.get(‘screenOn’)#返回True or False
解锁屏幕d.unlock()#安卓7.0试了可以,安卓9.0就不行了,实际行为是 1.启动activity: com.github.uiautomator,2.按下home键

2.设备按键事件

2.设备按键事件(所有的keyevent请点我

用法:d.press(keycode)

当前支持以下事件键值:,
home(主屏),back(返回上一级)
left,right,up,down,center(打开一个文本编辑框,可看到移动光标)
search(搜索框),enter(回车),delete ( or del 删除选中内容)
recent (recent apps),menu(菜单键) 这俩效果貌似一样的
volume_up(音量+),volume_down(音量-),volume_mute(静音)
camera(相机–没打开),power(电源键)

3.设备手势交互

3.设备手势交互

#x,y表示坐标,或填入小数(0.5,0.5)百分比表示屏幕的中心点,适用于:click,swipe,drag,long_click

单击d.click(x,y)
双击d.double_click(x,y,[duration])#两次点击之间的间隔默认0.1秒
长按d.long_click(x,y,[delay])#delay默认0.5秒

滑动d.swipe(sx,sy,ex,ey,[delay])#delay默认0.5秒
拖拽d.drag(sx,sy,ex,ey,[delay])#delay默认0.5秒

多点滑动:hw.swipe_points([(209,943),(541,973),(551,1265),(857,1265)],0.2)
按下并拖动(Beta):
d.touch.down(x,y)
time.sleep(0.1)
d.touch.move(x,y)
d.touch.up()

4.屏幕方向设定

4.屏幕方向设定

#打开拨号界面或短信界面:在android7.0上试了n,l,r均有效,android9.0上相册有受影响

n(natural),l(or left),r(right),u(upsidedown 这个无效)
direct = d.orientation#默认方向,输出natural
d.set_orientation(‘l’)

#锁定/解锁屏幕旋转
d.freeze_rotation()
d.freeze_rotation(false)

5.屏幕截图

5.屏幕截图

#要获得PIL格式的图像,需要安装pillow库,支持png、jpg格式:d.screenshot(“c:/name.jpg”)

#要获得opencv格式的图像,需要安装numpy和cv2库,用法如下:
img=xm.screenshot(format=‘opencv’)
cv2.imwrite(‘c:/test.jpg’,img)

#获得原始的jpeg数据
imgbin=d.screenshot(format=‘raw’)
open(“test.jpg”,“wb”).write(imgbin)

6.转储UI hierarchy

6.转储UI hierarchy
xml=d.dump_hierarchy()

7.打开通知中心/快捷设置

7.打开通知中心/快捷设置
d.open_notification()
d.open_quick_settings()

API 文档三

1.UI对象识别器Selector

1.UI对象识别器Selector

用法d(text=‘Clock’, className=‘android.widget.TextView’)

支持以下参数,
text, textContains, textMatches, textStartsWith
className, classNameMatches
description, descriptionContains, descriptionMatches, descriptionStartsWith
checkable, checked, clickable, longClickable
scrollable, enabled,focusable, focused, selected
packageName, packageNameMatches
resourceId, resourceIdMatches
index, instance

#点击: 设置→个性主题 :

方法一:
d(description=‘设置’, className=‘android.widget.ImageView’).click()
d(text=‘个性主题’, className=‘android.widget.TextView’).click()

方法二:
d(resourceId=“com.miui.home:id/icon_title”, text=“设置”).click()
d.xpath(‘//*[@text=“个性主题”]’).click()

2.获取UI对象状态及信息

2.获取UI对象状态及信息

d(text=“3D_H5”).exists
d.exists(text=“3D_H5”)
d(text=“3D_H5”).info

#获取/设置/清空编辑框内容
d(description=“请输入QQ号码或手机或邮箱”).get_text()
d(description=“请输入QQ号码或手机或邮箱”).set_text(“1234”)
d(description=“请输入QQ号码或手机或邮箱”).clear_text()

#获取控件中心位置坐标
x,y=d(text=“设置”).center()
#x,y = d(text=“设置”).center(offset=(0, 0)) # left-top x, y

#在UI选中对象上执行点击事件
d(text=“设置”).click(timeout=30)#最多延迟等待30秒,没找到该元素会抛出.UiObjectNotFoundError
d(text=“设置”).click(offset=(0.5, 0.5)) #百分比表示方法 默认点击中心坐标
d(text=“设置”).click(offset=(0, 0)) #点击坐标 左-上
d(text=“设置”).click(offset=(1, 1)) #点击坐标 右-下
d(text=“设置”).click_gone(maxretry=3, interval=1)#重复点击此元素3次,每次间隔1秒,若该元素消失则中止偿试并返回bool值
d(text=“设置”).long_click(timeout=3)#长按指定元素对象3秒

3.针对特定对象的手势动作

3.针对特定对象的手势动作

#在xx秒内拖动指定对象到指定坐标点(或指定对象位置)
d(text=“设置”).drag_to(500, 500, duration=0.1)
d(text=“设置”).drag_to(text=“安全中心”, duration=0.2)

#从UI对象的中心位置开始移动到它的边缘
支持4个方向:left,right,top,down
使用方法:d(text=“设置”).swipe(“up”,steps=100)#1 steps大约5ms,10 steps大约0.5秒,是一个按下→移动→弹起的过程。试了一下:steps太短上/上滑动等于单击,左/右移动等于快速滑动

#等待指定的对象出现,并返回bool值
d(text=“设置”).wait(timeout=3)#3秒内”设置“对象出现返回true,否则返回false

#等待指定的对象消失,并返回bool值
d(text=“设置”).wait(timeout=3)#3秒内”设置“对象消失”返回true,否则返回false

这个有两种情况1.如果当前界面无此对象,则直接返回false;2.如果当前界面有此对象,3内消失(最长等待3秒)返回true;否则返回false

#界面飞轮操作(就是按住滑一下,类似 鼠标滚轮滑动一次的行/列数)

#垂直滚动:
d(scrollable=True).fling()#默认垂直滚动条.vert可省略 为了可读性可加上,向下滚动
d(scrollable=True).fling.toEnd() 或 d(scrollable=True).fling.vert.toEnd()#垂直滑动:滑到最底部

d(scrollable=True).fling.toBeginning() 或 d(scrollable=True).fling.vert.toBeginning()#垂直滑动:滑到顶部
d(scrollable=True).fling.vert.forward()#垂直向上滑动
d(scrollable=True).fling.vert.backward()#t垂直向下滑动

#水平滚动(比如打开网页baidu,会在顶部的各个分类页签上切换):
d(scrollable=True).fling.horiz.toBeginning()#向左滑动
d(scrollable=True).fling.horiz.toEnd()#向右滑动
d(scrollable=True).fling.horiz.forward()#向左滑动
d(scrollable=True).fling.horiz.backward(max_swipes=1000)#向右滑动

#scroll滚动条操作
d(scrollable=True).scroll(steps=10)#默认垂直,向上滑动
d(scrollable=True).scroll.horiz.forward(steps=100)#向右滑动,1 steps约20ms
d(scrollable=True).scroll.vert.backward()#垂直:向下滑动
d(scrollable=True).scroll.horiz.toBeginning(steps=100, max_swipes=1000)#水平,向左滑动
d(scrollable=True).scroll.toEnd()#垂直:向下滑动到底部

#滚动直到指定的对象页面出现为止
d(scrollable=True).scroll.to(text=“琅琊榜”)#垂直的挺准
d(scrollable=True).scroll.horiz.to(text=“琅琊榜”)#这个水平的没搞明白……感觉不准确

4.监视器Watcher

4.监视器Watcher

#测试机为华为P7-安卓7.0

import uiautomator2 as u2
serialno = ‘KWG5T16603013752’
apk = ‘http://ip/test/eg.apk’
d = u2.connect_usb(serialno)
d.implicitly_wait(10.0)
d.watcher(“ok”).when(text=“仅允许本次安装”).click()#创建监视器
d.watcher(“ins”).when(text=“安装”).click()#创建监视器
d.watchers.watched=True#启动监视器
d.app_install(apk)#安装app
print(“all watchers:”,d.watchers,d.watchers.triggered)#打印所有监视器
d.watchers.reset()#重置监视器
print(“reset watchers:”,d.watchers.triggered)
d.watchers.remove(“ins”)#移除指定监视器
print(“reomve_ins.watcher”,d.watchers)
d.watchers.remove()#移除所有监视器
print(“remove_all.watcher”,d.watchers)

5.使用adb广播输入消息

5.使用adb广播输入消息

d(text=“备忘录”, className=“android.widget.TextView”).click()
d(text=“新建”, className=“android.widget.TextView”).click()
d.set_fastinput_ime(True) # 切换成FastInputIME输入法
d.send_keys(“你好hello”) # adb广播输入
d.clear_text() # 清除输入框所有内容
d.set_fastinput_ime(False) # 切换成正常的输入法
d.send_action(“search”) # 模拟输入法的搜索

send_action 说明
该函数可以使用的参数有 go search send next done previous

6.Toast显示和Xpath识别对象

6.Toast显示和Xpath识别对象

参考文章:UI2-xpath扩展,W3CSchoolXpath,xpath路径表达式,xpath快捷管理,xpath高级用法

#-- coding: utf-8 –
import uiautomator2 as u2
serialno = ‘7f3dec60’ # device adb serial
d = u2.connect_usb(serialno)

#比如操作微信底部按钮菜单,RelativeLayout[1]微信,[2]通讯录,[3]发现,[4]我
sl=d.xpath(‘//[@resource-id=“com.tencent.mm:id/bq”]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[3]‘).get()#
x,y=sl.center()
d.long_click(x,y)
‘’’
sl=d.xpath('//[@resource-id=“com.tencent.mm:id/li”]’)#操作搜索框
print(sl.exists,sl.get_last_match(),sl.get_text())
sl.set_text(“hello world”)#搜索框发送内容

if d(text=“文章”, className=“android.widget.TextView”).exists():#Selector搜索文本
print(“Got it-1 article”)
if d(resourceId=“com.tencent.mm:id/c2t”, className=“android.widget.TextView”).exists():#搜索id
print(“Got it-2 article”)

if d.xpath(‘//[@text=“文章”]‘).exists:
print(“Got it-3 article”)
if d.xpath(’//[@resource-id=“com.tencent.mm:id/c2t”]’).exists:
print(“Got it-4 article”)

if d(resourceId=“com.tencent.mm:id/c2t”, text=“文章”).exists():
print(“Got it-5 article”)
if d(resourceId=“com.tencent.mm:id/c2t”, text=“音乐”).exists():
print(“Got it-6 music”)
‘’’

#Toast消息显示

#d.toast.show(“Hello world”)
d.toast.show(“Hello world”, 1.0) # show for 1.0s, default 1.0s
#下边的get方法报错了
#d.toast.get_message(5.0, 10.0, “default message”)
#assert “Short message” in d.toast.get_message(5.0, default=“”)
#clear cached toast
#d.toast.reset()
#Now d.toast.get_message(0) is None

原文地址:
UIAutomator2的API文档(一)
https://www.cnblogs.com/sc912/p/11279228.html

UIAutomator2的API文档(二)
https://www.cnblogs.com/sc912/p/11283665.html

UIAutomator2的API文档(三)
https://www.cnblogs.com/sc912/p/11284660.html

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值