Python__模块(OPT-自动化-移动端)__uiautomator2

简介

自动化测试(App端)

安装

pip install --pre uiautomator2 

pip install -U weditor 界面调试工具

adb工具下载(SDK Platform-Tools) -> 配置环境变量


调试

详细版

【1】手机开发者模式->USB调试打开

【2】启动weditor服务 python -m weditor(界面调试)

【3】出现的页面->Connect | Dump Hierarchy (手机画面展示)

【4】下载 adb(SDK Platform-Tools 工具)->配置环境变量

  adb(Android Debug Bridge(安卓调试桥) 用于通过电脑端与模拟器或者是设备之间的交互)

【5】终端:adb devices 查看连接的设备(查看设备)

【6】手机和电脑在同一个网络

【7-1】adb开启

  手机通过USB连接电脑,先开启远程adb模式

  终端

  1. adb tcpip 5555 (指定一个非默认的端口号)
  2. adb connect 192.168.1.27:5555 (断开USB 后,执行)
  3. adb devices 查看连接状态 (显示为devices表示连接成功)

  如果显示状态为offline时,需要重启adb进程

  • adb kill-server  // 命令行执行
  • adb start-server  // 命令行执行

【7-2】python代码进行操作(uiautomator2)

简化版

1.查看设备信息:cmd-> adb devices 查看连接的设备(手机/模拟器...)
1-1.指定端口:cmd-> adb tcpip 5555
1-2.连接端口(方法1):cmd-> adb connect 192.168.1.30:5555 (例子:手机ip+端口号)
1-2.连接端口(方法2):weditor-> 192.168.1.30:5555/设备信息 (例子:手机ip+端口号)
1-2.连接端口(方法3):uiautomator


参考代码

【综合】device

import uiautomator2 as u2
def function():
    ip_win = "emulator-5554"       # 本地设备:模拟器/手机 (例子:雷神模拟器)
    ip_net = "192.168.1.158:5566"  # 网络设备:手机 (前提条件:先用adb工具指定一个端口)
    device = u2.connect(ip_win)    # 连接设备
    print(device.device_info)      # 查看设备信息
                                   # @注释 / 参数
                                   # app_current        获取正在运行的app
                                   # app_list_running() 列举正在运行的多个app
                                   # --------------------------------------- /
    return device

【综合】安装 / 卸载 / 清除 

device = function()
''' 安装软件 '''
apk_url = "https://imtt.dd.qq.com/16891/88AEDCCDD4C729268E4D7F95753C38ED.apk?fsname=com.ss.android.article.browser_1.0.8_618.apk&csr=1bbd"
device.app_install(apk_url)
''' 卸载软件 '''
# device.app_uninstall('com.ss.android.article.browser')
''' 清除软件数据 '''
# device.app_clear('com.ss.android.article.browser')

【综合】运行 / 打开 / 关闭

''' 运行软件 '''
device = function()
''' 打开软件 '''
device.app_start("com.ss.android.article.browser")
''' 关闭软件 '''
# device.app_stop('com.ss.android.article.browser')
# app_stop_all  # 关闭所有应用
# app_stop_all(excludes=['com.examples.demo']) # 停止所有应用程序,除了com.examples.demo

【综合】延迟缓冲

''' wait方法 '''
# 智能等待(不需要调用time.sleep方法)
"""
    方法1-device.wait_timeout=30      # 单位(秒)
    方法2-device.implicitly_wait(30)  # 默认等待
    device.app_start('',wait=True)
    device.wait_activity()       # 等待页面加载完成
    device.wait()                # 等待元素出现
    device.wait_gone()           # 等待元素消失
    device.exist()               # 等待元素是否存在、
    click(timeout=50)            # 设置点击超时时间(单位:秒)

    -> 断言(预期结果是否等于实际结果的过程)
    # toast 弹框
    assert device.toast.get_message() # 例子:手机号或密码不能为空
"""
# 例子
"""
    d = device
    d.wait_timeout = 30     # 全局的等待时间
    d.implicitly_wait(30)
    d.app_start(self.app_name,wait=True)
    d.wait_activity()       # 等待页面出现
"""
"""
    d(text='xxxxx').wait()         # 等待某个元素出现
    d(text='xxxxx').wait_gone()    # 等待某个元素消失
    d(text='xxxxx').exists()       # 等待某个元素是否存在
"""

【综合】元素定位

''' 判断元素 '''
# 判断按钮是否存在
# if device(定位元素).exists()

''' 元素定位 '''
"""
    元素定位方式:
            text app名称
            textContaints 包含 app名称 (例子:demo浏览器,可以输入为demo)
            classname
            description
            checkable,checked
            scrollable
            packgeName,
            resourceId,
            index,instance
    元素的上下级:
            上级: 页面外层
            下级: 页面内层 child() 例子: device(resourceId='').child(resourceId='')
            同级元素: sibling()    例子: device(className='').sibling(className='')
            -> 根据页面相对位置元素定位(速度较慢)
            left,right,up,down 例子:device(resourceId='').left().click()
"""
"""device(resourceId='')"""

''' 同类型多个元素-方法1 ''' 
# device(resourceId='',instance=2) 
# instance=2 属性获取第3个元素"""

''' 同类型多个元素-方法2 '''
# device(resourceId='')[2]"""

【综合】获取内容

''' 获取内容 '''
# get_text() 

''' 设置内容 '''
# set_text() 

''' 清空内容 '''
# device(resourceId='').clear_text() 

【综合】点击 / 滑动 / 拖拽

#===== Event事件 =====#

''' 属性 '''
"""
    单位:秒
    timeout = 1   # 时间延迟(等待的范围)
    duration = 1  # 鼠标事件总时间操作
"""

''' 点击 '''
device(text="xx浏览器").click()
# double_click()                 # 双击
# long_click(x, y, duration=0.5) # 长按控件

''' 滑动-方法1 '''
# swipe(10,800,700,800) # 绝对定位滑动
# swipe(startX,startY,endX,endY,duration=0.1,step=None) # 滑动 (起始点->结束点)
# swipe('down',steps=10) # 向下滑动,整个滑动的事件
# swipe_ext('left')      # 向左滑动

''' 滑动-方法2 '''
# swipe_ext('right')                    # 手指右滑 参数可选择填写'right','left','up','down'
# swipe_ext('right', scale=0.9)         # scale默认为0.9,即滑动距离为屏幕宽度的90%
# swipe_ext('right', box=(0,0,100,100)) # 在(0,0)->(100,100)区域做滑动

''' 滑动-方法3 '''
# 使用Direction作为参数
# from uiautomator2 import Direction
# swipe_ext(Direction.FORWARD)        # 页面下翻 等价于d.swipe_ext('up')
# swipe_ext(Direction.BACKWARD)       # 页面上翻
# swipe_ext(Direction.HORIZ_FORWARD)  # 页面水平右翻
# swipe_ext(Direction.HORIZ_BACKWARD) # 页面水平左翻
"""

''' 滑动-其它 '''
# swipe_point():滑动经过多个点,多用于九宫格解锁
                 # @例子 /
                 # swipe_points([(x0,y0),(x1,y1),(x2,y2)],0.2)
                 # @参数 /
                 # 从(x0,y0)->(x1,y1)->(x2,y2)
                 # 0.2表示必须在0.2s之内从完成滑动
                 # ----------------------------- /

''' 拖拽 '''
# drag(sx, sy, ex, ey, duration=0.5)

【综合】按键操作

"""
按键操作:
        press('home)  首页
        press('back')
        press('left 或 right 或 up 或 down')
        press('center')
        press('menu')
        press('search') 搜索功能
        press('enter')
        press('delete (or del)')
        press('recent(recent apps)') 最近使用的app
        press('camera') 拍照键
        press('power')  电源键
        更多按键功能 进行文档查找
"""
# 例子
device = function ()
device.press('home')  # 模拟按键
device(resourceId='').send_keys('输入内容')

【综合】滚动操作

d = device

''' 垂直滚动到页面顶部 / 横向滚动到最左侧 '''
d(scrollable=True).scroll.toBeginning()
d(scrollable=True).scroll.horiz.toBeginning()

''' 垂直滚动到页面最底部 / 横向滚动到最右侧 '''
d(scrollable=True).scroll.toEnd()
d(scrollable=True).scroll.horiz.toEnd()

''' 垂直向后滚动到指定位置 / 横向向右滚动到指定位置 '''
d(scrollable=True).scroll.to(description='指定位置')
d(scrollable=True).scroll.horiz.to(description='指定位置')

''' 垂直向前滚动(横向同理)'''
d(scrollable=True).scroll.forward()

''' 垂直向前滚动到指定位置(横向同理) '''
d(scrollable=True).scroll.forward.to(description='指定位置')

【综合】文件操作 

device = function()
''' 发送文件 -> 电脑 '''
# device.pull("/image/pt.jpg", "./test.png")  # 参数(手机路径,电脑路径)
''' 发送文件 -> 手机 '''
# device.push('./pt.jpg','/data/')            # 参数(电脑文件,手机存储路径)

【综合】屏幕操作

device = function()

''' 屏幕活动 '''
# screen_on()   # 亮屏
# screen_off()  # 熄屏
# unlock()      # 解锁屏幕

''' 屏幕大小 '''
# size = device.window_size()  # 屏幕大小
# print(size)

''' 屏幕旋转 '''
# d=device
# orientation = d.orientation  # 获取屏幕方向 / 
                               # 取值为{'natural', 'left', 'right', 'upsidedown'}
                               # ------------------------------------------------ /
# d.freeze_rotation()          # 锁定屏幕方向
# d.freeze_rotation(True)      # 解除锁定屏幕方向

''' 设置屏幕方向 '''
# d.set_orientation('left')      # 向左转为横屏
# d.set_orientation('right')     # 向右转为横屏
# d.set_orientation('natural')   # 转为竖屏

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

''' 普通截屏 '''
# device.screenshot("test.png")

''' 自定义截屏 '''
"""
from PIL import ImageFilter
im = device.screenshot()
im.save('test1.png')
im2 = im.filter(ImageFilter.BLUR) # 滤镜设置(模糊处理)
im3 = im.resize((90,160))         # 调整屏幕大小
im2.save('t1.png')
im3.save('t2.png')
"""

【其它】App连接

import uiautomator2 as u2

# 连接方法1: USB连接
# cmd->adb devices 命令查看
"""
device = u2.connect('016294c8')
print(device.device_info)
"""

# 连接方法2: WIFI连接
device = u2.connect("192.168.1.123:5566")
print(device.device_info)  # 查看设备信息
device.app_start("com.android.contacts")  # 打开 通讯录
# device.swipe(10,800,700,800)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vip飞梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值