python+uiautomator2自动化测试一

1、python端安装uiautomator2

pip install --pre uiautomator2

pip install pillow

2、手机端安装atx-agent(守护进程)

python -m uiautomator2 init

安装过程中手机要同意安装ATX,安装成功之后手机端会出现一个ATX应用

python+uiautomator2自动化测试一_第1张图片

3、通过USB或者wifi连接设备

a、通过usb连接(device name通过adb devices获取)
python+uiautomator2自动化测试一_第2张图片

import uiautomator2 as u2
d = u2.connect_usb('2aaf3398')
print(d.info)

b、通过wifi连接:保持PC和手机使用的一个WIFI,查看手机连接WIFI的IP地址

import uiautomator2 as u2 
d = u2.connect('ip地址')
print(d.info)

4、定位元素

一般通过Android SDK自的uiautomatorviewer查看元素,但是运行uiautomator2的时候,uiautomatorviewer.bat无法运行

可以使用weditor进行元素定位,首先安装pip install --pre weditor

然后启动:python -m weditor,运行此命令打开网页http://localhost:17310/

连接手机,第一步:选择手机类型ios/android,第二步:填写手机IP地址(可以在设置-关于手机查看),第三步:点击connect连接手机,第四步:点击reload加载手机界面

python+uiautomator2自动化测试一_第3张图片

python+uiautomator2自动化测试一_第4张图片

常用的定位方式:

ResourceId定位:
d(resourceId=".......").click()

Text定位:
d(text="......").click()

Description定位:
d(description=".......").click()

ClassName定位:
d(className="........").click()

操作控件

# 点击
d(text=".....").click()

# 长按
d(text=".....").long_click()

#滑动
d.swipe(x1, y1, x2, y2)
d.swipe(x1, y1, x2, y2, steps=10)

# 等待元素的出现
d(text=".....").wait(timeout=10.0)

#set_text只能用来输入 英文
d(text="......").set_text(".....")

#获取到输入框焦点之后,可以通过切换输入法send_keys输入中文
d.set_fastinput_ime(True)
d.send_keys(".....")
d.set_fastinput_ime(False) # 输入法用完关掉

#截图:
d.screenshot("XXX.jpg")

#获取图层信息:
xml = d.dump_hierarchy()

#判断元素是否存在
if d(text=".....").exists:
    print('pass')
else
    print('fail')

 

 

 

你可能感兴趣的:(python+uiautomator2自动化测试一)