Python-UIAutomator2

工作原理:

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

整个过程

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

安装

安装python3:

    python官网下载地址: https://www.python.org/downloads/

安装adb:

    从谷歌官网下载Android Platform Tools https://developer.android.com/studio/releases/platform-tools.html,解压,并加包含adb.exe的目录加入到系统的PATH中。

安装uiautomator2

    pip install --pre -U uiautomator2

    pip install pillow

移动端设备(Android)

 

初始化

部署相关的守护进程。

电脑连接上一个手机或多个手机, 确保adb已经添加到环境变量中,执行下面的命令会自动安装本库所需要的设备端程序:uiautomator-server 、atx-agent、openstf/minicap、openstf/minitouch

python -m uiautomator2 init

安装完成,设备上会多一个uiautomator的应用。

注意:如果执行python -m uiautomator2 init命令报PIL相关错误,卸载pillow(pip uninstall pillow) 重新安装即可  

 

 

调用uiautomator2的过程

    1.配置手机设备参数,设置具体操作的是哪一台手机

    2.抓取手机上应用的控件,制定对应的控件来进行操作

    3.对抓取到的控件进行操作,比如点击、填写参数等。

 

 

配置手机设备参数

python-uiautomator2连接手机的方式有两种,一种是通过WIFI,另外一种是通过USB。两种方法各有优缺点。

WIFI最便利的地方要数可以不用连接数据线,USB则可以用在PC和手机网络不在一个网段用不了的情况。

 

1. 使用WIFI连接

手机获取到手机的IP,并确保电脑可以PING通手机。手机的IP可以在设置-WIFI设置里面获取到。

比如手机的IP是192.168.2.137,连接设备的代码为

import uiautomator2 as u2
d = u2.connect('192.168.2.137')

 

2. 使用USB连接

手机的序列号可以通过adb devices获取到,假设序列号是1234abc,连接代码为

import uiautomator2 as u2

d = u2.connect_usb('1234abc')

 

 

测试

import uiautomator2 as u2

d = u2.connect_usb('ce76de0e')

print(d.info)

打印结果:

{'currentPackageName': 'com.sec.android.app.launcher', 'displayHeight': 1920, 'displayRotation': 0, 'displaySizeDpX': 411, 'displaySizeDpY': 731, 'displayWidth': 1080, 'productName': 'c5pltezc', 'screenOn': True, 'sdkInt': 26, 'naturalOrientation': True}

获得设备基本信息:

设备概要信息: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

 

 

元素定位

1、查看app控件

 

我们可以借助Android SDK自的uiautomatorviewer查看元素,这就要求手机必须以USB的方式连接PC,我前面使用的是WIFI连接进行连接的。所以,openatx提供了另外一个工具weditor 来解决这个问题。

GitHub地址:https://github.com/openatx/weditor

 

 

(1)、安装:

pip install --pre --upgrade weditor

(2)、使用

python3 -m weditor

(3)、工具打开

默认会通过浏览器打开页面:http://atx.open.netease.com/

 

(4)工具的操作步骤

选择android、输入手机或者模拟器的ip+端口,点击connect

dump hierarchy是用来刷新页面的

鼠标点击想要的元素,就可以查看他们的控件了

 

2、主要语法

(1)启动app

        d.app_start("com.addcn.android.house591")

 

(2)关闭app

        d.app_stop("com.addcn.android.house591")

 

(3)ResourceId定位

        d(resourceId="com.addcn.android.house591:id/ad_banner").click()

 

(4)Text定位

        d(text="设置").click()

 

(5)Description定位

        d(description="..").click()

 

(6)ClassName定位

        d(className="android.widget.TextView").click()

 

(7)xpath定位

        d.xpath("//*[@content-desc='收藏']").click()

 

3、其他操作

 

(1)#组默认元素等待超时(秒)

        cls.d.wait_timeout = 20.0  #默认20

 

(2)元素拖拽

(3)开关点击

    d(A).left(B), selects B on the left side of A.

    d(A).right(B), selects B on the right side of A.

    d(A).up(B), selects B above A.

    d(A).down(B), selects B under A.

    例如:

    #选择“Wi-Fi”右侧的“开关”

    d(text="Wi‑Fi").right(className="android.widget.Switch").click()

 

 

 

(4)获取/统计某个相同条件的数目

    d(text="Add new").count

    或者

    len(d(text="Add new"))

 

    得知数目之后,我们可以通过索引去定位

    d(text="Add new")[0]

    d(text="Add new")[1]

 

    也可以遍历:

    for view in d(text="Add new"):

        view.info

 

 

    (5)截图

    #截取屏幕截图并保存到计算机上的文件中,要求Android> = 4.2。

    d.screenshot( “ 路径/home.jpg ”)  # get PIL.Image格式化图像。当然,你需要首先安装pillow 

    image = d.screenshot()      # default format =“pillow”

    mage.save( “ home.jpg ”)        #或home.png。目前,只有PNG和JPG支持

    #得到OpenCV的格式图像。当然,你需要先安装numpy和cv2

    import cv2

    image = d.screenshot( format = ' opencv') cv2.imwrite( ' home.jpg '图像)#获取原始JPEG数据 imagebin =    d.screenshot(格式= '原始') 打开( “ some.jpg ”, “ WB ”).WRITE(imagebin)

 

(6)手势操作

        1、单击

            d( text = “ Settings ”).click()

            d.click(x,y)

         2、 双击

            d.double_click(x,y)

            d.double_click(x,y,0.1) #默认两次点击之间间隔0.1秒

        3、长按

            d( text = “ Settings ”).long_click()

            d.long_click(x,y)

     d.long_click(x,y,0.5) #长按0.5秒(默认)

注意:单击,滑动,拖动操作支持百分比位置值。例: d.long_click(0.5,0.5) 表示长按屏幕中心

 

        3、将对象拖向另一个点或另一个UI对象

        #笔记:拖不能用于为Android <4.3。

        #将UI对象拖动到屏幕点(x,y),0.5秒后

        d( text = “设置”).drag_to(x,y, duration = 0.5)

        #将UI对象拖动到另一个(中心位置) UI对象,在0.25秒

        d( text = “设置”).drag_to( text = “ Clock ”, duration = 0.25)

 

        4、在屏幕上滑动

        # swipe from (sx, sy) to (ex, ey)

        d.swipe(sx, sy, ex, ey)

 

        # swipe from (sx, sy) to (ex, ey) with 10 steps

        d.swipe(sx, sy, ex, ey, steps=10)

 

       滑动点   多用于九宫格解锁,提前获取到每个点的相对坐标(这里支持百分比)

       # swipe from point(x0, y0) to point(x1, y1) then to point(x2, y2)

   # time will speed 0.2s bwtween two points

     d.swipe((x0, y0), (x1, y1), (x2, y2), 0.2)

 

        5、在屏幕上拖拽

            # drag from (sx, sy) to (ex, ey)

            d.drag(sx, sy, ex, ey)

            # drag from (sx, sy) to (ex, ey) with 10 steps

            d.drag(sx, sy, ex, ey, steps=10)

        6、打开/关闭屏幕

      d.screen_on()#打开屏幕

      d.screen_off()#关闭屏幕

        7、获取当前屏幕的状态

             d.info.get('screenOn')    #True表示屏幕打开  False表示屏幕关闭,   screenOn区分大小写

 

(7)获取对象信息和状态

    1、d(text="Settings").exists

        #如果存在则为True,否则为假

        or d.exists(text="Settings") # 进一步使用 d(text="Settings").exists(timeout=5)

        # 等待设置出现在3S,相同.wait(3)

 

    2、检索特定UI对象的信息

        d(text="Settings").info

 

    3、获取/设置/清除可编辑字段的文本(例如,EditText小部件)

         d(text = “ Settings ”).get_text()   # get widget text

        d(text = “ Settings ”).set_text(“ My text ... ”)   #设置文本

        d(text = “ Settings ”).clear_text( )   #清除文字、

    4、输入中文

        d.send_keys("你好 Hello")

    5. 切换输入法及输入法用完关掉

   d.set_fastinput_ime(True)
   d.set_fastinput_ime(False) 

(8)系统常用按键

    # press home key

     d.press.home()

    # press back key

    d.press.back()

    # the normal way to press back key

    d.press("back")----亲测可用

    # press keycode 0x07('0') with META ALT(0x02) on

    d.press(0x07, 0x02)

    home                   #手机Home键

    back                   #手机返回键

    left                   #对应键盘上的向右键<-

    right                  #对应键盘上的向右键->

    up                    #对应键盘上的向上键

    down                   #对应键盘上的向下键

    center                  #选中?

    menu                   #菜单

    search                  #查找?

    enter                  #对应键盘上的Enter键

    delete(or del)                          #对应键盘上的DEL键 用于删除

    recent(recent apps)                  #任务切换

    volume_up                #声音向上调整

    volume_down               #声音向下调整

    volume_mute               #静音按键

    camera                  #拍照

    power                   #电源键

 

(9)打开/关闭屏幕

  1.  d.screen_on()#打开屏幕

  2.  d.screen_off()#关闭屏幕

(10)获取当前屏幕的状态

     d.info.get('screenOn')    #True表示屏幕打开  False表示屏幕关闭

(11)

注:

1、使用前初始化

python -m uiautomator2 init

2、打开weditor工具

python3 -m weditor

 

 

参考 https://testerhome.com/topics/11357

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值