文章目录

  • 一、简介
  • 二、支持平台及语言
  • 三、工作原理
  • 四、安装
  • 4.1 环境要求
  • 4.2 安装adb
  • 4.3 安装uiautomator2
  • 4.4 设备安装atx-agent
  • 4.5 安装weditor
  • 4.6 应用及操作
  • 4.6.1 调用uiautomator2的过程
  • 4.6.2 设备连接方法
  • 4.6.3 检查并维持设备端守护进程处于运行状态
  • 4.6.4 打开调试开关
  • 4.6.5 安装应用
  • 4.6.6 启动应用
  • 4.6.7 停止应用
  • 4.6.8 停止所有正在运行的应用程序
  • 4.6.9 跳过弹窗,禁止弹窗
  • 4.6.10 Session
  • 4.6.11 获取设备信息
  • 4.6.12 获取应用信息
  • 4.6.13 推拉文件
  • 4.6.14 关键事件
  • 4.6.15 手势与设备的交互
  • 4.6.16 屏幕相关的
  • 4.6.17 选择Ui对象
  • 4.6.18 UI对象的六种定位方式
  • 4.6.19 Toast
  • 4.6.20 XPath
  • 五、Google uiautomator与uiautomator2的区别
  • 一、简介

      uiautomator2是一个python库,用于Android的UI自动化测试,其底层基于Google uiautomator,Google提供的uiautomator库可以获取屏幕上任意一个APP的任意一个控件属性,并对其进行任意操作。
    GitHub地址:https://github.com/openatx/uiautomator2

    二、支持平台及语言

      python-uiautomator2封装了谷歌自带的uiautomator2测试框架,提供便利的python接口。他允许测试人员直接在PC上编写Python的测试代码,操作手机应用,完成自动化,大大提高了自动化代码编写的效率。

    三、工作原理


    如图所示,python-uiautomator2主要分为两个部分,python客户端,移动设备

  • python端:运行脚本,并向移动设备发送HTTP请求
  • 移动设备:移动设备上运行了封装了uiautomator2的HTTP服务,解析收到的请求,并转化成uiautomator2的代码。
  • 整个过程

    1. 在移动设备上安装atx-agent(守护进程),随后atx-agent启动uiautomator2服务(默认7912端口)进行监听
    2. 在PC上编写测试脚本并执行(相当于发送HTTP请求到移动设备的server端)
    3. 移动设备通过WIFI或USB接收到PC上发来的HTTP请求,执行制定的操作

    四、安装

    4.1 环境要求

  • python 3.6+
  • android 4.4+
  • 4.2 安装adb

      如命令行可以执行adb devices,则跳过此步骤
      从谷歌官网下载Android Platform Tools, 解压,并加包含adb.exe的目录加入到系统的PATH中。

    4.3 安装uiautomator2

    pip install --pre uiautomator2 
    pip install pillow (如果需要截图,可安装pillow)
    

    4.4 设备安装atx-agent

    首先设备连接到PC,并能够adb devices发现该设备。
    执行下面的命令会自动安装本库所需要的设备端程序:uiautomator-server,atx-agent,openstf / minicap,openstf / minitouch

    # init就是所有USB连接电脑的手机上都安装uiautomator2
    python -m uiautomator2 init
     
    # 指定手机安装uiautomator2, 用 --mirror
    python -m uiautomator2 init --mirror --serial $SERIAL
    
    # 嫌弃慢的话,可以用国内的镜像
    python -m uiautomator2 init --mirror
    

    最后提示success,代表atx-agent初始化成功。

    4.5 安装weditor

    有了这个,方便我们快速的识别手机上的元素,方便写代码

    pip install -U weditor   #pip install --pre weditor
    

    安装好之后,就可以在命令行运行 weditor --help 确认是否安装成功了。

    Windows系统可以使用命令在桌面创建一个快捷方式:

    python -m weditor –shortcut
    # 或weditor --shortcut
    

    在windows cmd中执行上述命令后,会在桌面上创建一个快捷方式,如下图:

    启动方法:

  • 方法1:命令行直接输入 weditor 会自动打开浏览器,输入设备的ip或者序列号,点击Connect即可
  • 方法2:桌面上双击WEditor快捷方式即可
  • 方法3:命令行中执行 python -m weditor
  • 启动后浏览器会自动打开一个网页,如下图:

    重点说下这个部分

      如何与手机连接起来呢?就是通过手机序列号或IP来实现的。打开cmd,输入adb devices,查看手机序列号,输入框中填写设备的IP或者设备的Serial(序列号)。之后点击Connect,如果一切正常就会出现一个绿色的叶子

      点击蓝色的Reload,就可以在网页上看到手机的界面了。非常的强大。我们可以看到手机元素的各种定位方法,在UI自动化写代码的时候,真的是非常的方面,手机页面和weditor是实时同步的。

    【推荐】AppetizerIO 所见即所得脚本编辑器
    AppetizerIO 提供了对uiautomator2的深度集成,可以图形化管理ATX设备,还有所见即所得脚本编辑器

  • 到网站下载直接打开,首次使用需要注册账号
  • 设备管理 界面里可以检查设备是否正常init,起停atx-agent,抓取atx-agent.log文件
  • APP测试->脚本助手调出脚本助手,实时界面同步,点击界面直接插入各种代码,同时支持uiautomator和Appium
  • 4.6 应用及操作

    4.6.1 调用uiautomator2的过程

    1. 配置手机设备参数,设置具体操作的是哪一台手机
    2. 抓取手机上应用的控件,制定对应的控件来进行操作
    3. 对抓取到的控件进行操作,比如点击、填写参数等

    4.6.2 设备连接方法

      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,您需要确保只有一个设备连接到计算机。

    4.6.3 检查并维持设备端守护进程处于运行状态

    d.healthcheck()
    

    4.6.4 打开调试开关

    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}}
    '''
    

    4.6.5 安装应用

    只能从URL安装

    d.app_install('http://some-domain.com/some.apk') #引号内为下载apk地址
    

    4.6.6 启动应用

    d.app_start('包名', '界面名')
    

    4.6.7 停止应用

    #相当于'am force-stop'强制停止应用
    d.app_stop('com.example.hello_world')  #引号内为包名称
    #相当于'pm clear' 清空App数据
    d.app_clear('com.example.hello_world')
    

    4.6.8 停止所有正在运行的应用程序

    # 停止所有
    d.app_stop_all()
    # 停止所有应用程序,除了com.examples.demo
    d.app_stop_all(excludes=['com.examples.demo'])
    

    4.6.9 跳过弹窗,禁止弹窗

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

    4.6.10 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()
    
  • 链接正在运行的应用
  • sess = d.session("com.netease.cloudmusic",attach = True)
    
  • 检测应用崩溃
  • # App正在运行时
    sess(text="Music").click() # 操作是正常的
     
    # App崩溃时
    sess(text="Music").click() # 引发会话中断错误SessionBrokenError
    # session下的其他函数调用也会引发SessionBrokenError错误
    
    # 检查会话是否正确。
    # 警告:函数名将来可能会更改
    sess.running() # True or False
    

    4.6.11 获取设备信息

  • 获取基本信息
  • 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)
    
  • 获取当前应用程序信息。对于某些android设备,输出可以为空(参见输出示例3)
  • 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'}
    # 输出示例 3: {'package': None, 'activity': None}
    
  • 获取设备序列号
  • 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'}
    

    4.6.12 获取应用信息

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

    4.6.13 推拉文件

  • 将文件推送到设备
  • # 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")
    

    4.6.14 关键事件

  • 打开/关闭屏幕
  • d.screen_on() #打开屏幕 
    d.screen_off() #关闭屏幕
    
  • 获取当前屏幕状态
  • d.info.get(' screenOn ') #需要 Android >= 4.4
    
  • 硬键盘和软键盘操作
  • 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") #电源键
    
  • 解锁屏幕
  • d.unlock()
    # 相当于
    # 1. 发射活动:com.github.uiautomator.ACTION_IDENTIFY
    # 2. 按home键
    

    4.6.15 手势与设备的交互

    # 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) # 表示长按屏幕中心
    

    4.6.16 屏幕相关的

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

    4.6.17 选择Ui对象

    选择器是一种方便的机制,用于在当前窗口中标识特定的UI对象。

    #选择带有文本'Clock'的对象,它的类名是'android.widget.TextView'
    d(text='Clock', className='android.widget.TextView')
    

    选择器支持以下参数。有关详细信息,请参阅 UiSelector Java doc for detailed information

  • 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
  • # 1、检查特定的UI对象是否存在
    d(text="Settings").exists # 返回布尔值,如果存在则为True,否则为False
    d.exists(text="Settings") # 另一种写法
    # 高级用法
    d(text="Settings").exists(timeout=3) # 等待'Settings'在3秒钟出现
    
    # 2、获取特定UI对象的信息
    d(text="Settings").info
    
    # 3、获取/设置/清除可编辑字段的文本(例如EditText小部件)
    d(text="Settings").get_text()  #得到文本小部件
    d(text="Settings").set_text("My text...")  #设置文本
    d(text="Settings").clear_text()  #清除文本
    
    # 获取Widget中心点
    d(text="Settings").center()
    #d(text="Settings").center(offset=(0, 0)) # 基准位置左前
    

    4.6.18 UI对象的六种定位方式

    UI对象有六种定位方式,text、resourceId、description、className、xpath、坐标

  • 执行单击UI对象
  • # 1、text定位单击
    d(text="Settings").click()
    d(text="Settings", className="android.widget.TextView").click()
    
    # 2、resourceId定位单击
    d(resourceId="com.ruguoapp.jike:id/tv_title", className="android.widget.TextView").click() 
    
    # 3、description定位单击
    d(description="设置").click()
    d(description="设置", className="android.widget.TextView").click()
    
    # 4、className定位单击
    d(className="android.widget.TextView").click()
    
    # 5、xpath定位单击
    d.xpath("//android.widget.FrameLayout[@index='0']/android.widget.LinearLayout[@index='0']").click()
    
    # 6、坐标单击
    d.click(182, 1264)
    
    
    # 等待元素出现(最多10秒),出现后单击 
    d(text="Settings").click(timeout=10)
    # 在10秒时点击,默认的超时0
    d(text='Skip').click_exists(timeout=10.0)
    # 单击直到元素消失,返回布尔
    d(text="Skip").click_gone(maxretry=10, interval=1.0) # maxretry默认值10,interval默认值1.0
    # 点击基准位置偏移
    d(text="Settings").click(offset=(0.5, 0.5)) # 点击中心位置,同d(text="Settings").click()
    d(text="Settings").click(offset=(0, 0)) # 点击左前位置
    d(text="Settings").click(offset=(1, 1)) # 点击右下
    
  • 执行双击UI对象
  • d(text="设置").double_click() #双击特定ui对象的中心
    d.double_click(x, y, 0.1)#两次单击之间的默认持续时间为0.1秒
    
  • 执行长按UI对象
  • # 长按特定UI对象的中心
    d(text="Settings").long_click()
    d.long_click(x, y, 0.5) # 长按坐标位置0.5s默认
    
  • 将UI对象拖向另一个点或另一个UI对象
  • # Android<4.3不能使用drag.
    # 在0.5秒内将UI对象拖到屏幕点(x, y)
    d(text="Settings").drag_to(x, y, duration=0.5)
    # 将UI对象拖到另一个UI对象的中心位置,时间为0.25秒
    d(text="Settings").drag_to(text="Clock", duration=0.25)
    
  • 特定UI对象的手势操作
    支持两种手势:从边缘到中心、从中心到边缘
  • #注意:缩放要到安卓4.3才能设置。
    #从边缘到中心
    d(text="Settings").pinch_in(percent=100, steps=10)
    # 从中心到边缘
    d(text="Settings").pinch_out()
    
  • 等待,直到特定的UI出现或消失
  • # 等待ui对象出现
    d(text="Settings").wait(timeout=3.0) # 返回布尔值
    # 等待ui对象的消失
    d(text="Settings").wait_gone(timeout=1.0)
    # 默认超时为20秒。有关详细信息,请参阅全局设置
    

    4.6.19 Toast

  • 展示Toast
  • d.toast.show("Hello world")
    d.toast.show("Hello world", 1.0) # 显示为1.0,默认为1.0
    
  • 获取 Toast
  • # [参数]
    # 5.0: 最大等待超时。默认的10.0
    # 缓存时间10.0s。如果最近10s已经出现toast,则返回缓存toast。默认10.0(将来可能会有变化)
    # 如果最终没有toast,返回"default message"。默认没有
    d.toast.get_message(5.0, 10.0, "default message")
    
    # 常见的使用
    assert "Short message" in d.toast.get_message(5.0, default="")
    
    #清楚缓存toast
    d.toast.reset()
    # Now d.toast.get_message(0) is None
    

    4.6.20 XPath

    例如: 其中一个节点的内容

    <android.widget.TextView
      index="2"
      text="05:19"
      resource-id="com.netease.cloudmusic:id/qf"
      package="com.netease.cloudmusic"
      content-desc=""
      checkable="false" checked="false" clickable="false" enabled="true" focusable="false" focused="false"
      scrollable="false" long-clickable="false" password="false" selected="false" visible-to-user="true"
      bounds="[957,1602][1020,1636]" />
    

    xpath定位和使用时,有些属性的名字有修改需要注意

    description -> content-desc
    resourceId -> resource-id
    

    常见用法:

    # 等待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")]
    

    五、Google uiautomator与uiautomator2的区别

    1. API相似但是不完全兼容
    2. uiautomator2是安卓项目,而uiautomator是Java项目
    3. uiautomator2可以输入中文,而uiautomator的Java工程需借助utf7输入法才能输入中文
    4. uiautomator2必须明确EditText框才能向里面输入文字,uiautomator直接指定父类也可以在子类中输入文字
    5. uiautomator2获取控件速度比uiautomator快

    文章参考:https://vic.kim/2019/05/20/UIAutomator2%E7%9A%84%E4%BD%BF%E7%94%A8/

    来源:adorable_

    物联沃分享整理
    物联沃-IOTWORD物联网 » UIAutomator2的使用教程

    发表评论