通过python+uiautomator2可以实现对安卓手机的自动控制。这里用雷电模拟器进行测试,真实手机的控制方法与此相仿。
一、准备工作
雷电模拟器运行前需要关闭Hyper-V,否则启动雷电模拟器时可能会造成电脑蓝屏……

网络桥接
打开雷电模拟器的网络桥接模式

安装uiautomator2
pip install --pre uiautomator2
pip install pillow
初始化
执行下面的命令会自动安装本库所需要的设备端程序:uiautomator-server 、atx-agent、openstf/minicap、openstf/minitouch
python -m uiautomator2 init
安装完成,设备上会多一个uiautomator的应用。

打开这个应用可以查看设备参数,也可以在这里查看本机IP地址。

二、weditor
可以通过weditor来查看元素,方便进行脚本的编写。而且weditor还可以自动生成代码,非常方便。
安装
pip install --pre --upgrade weditor
使用
Python3 -m weditor
在页面左上角选择Android,输入设备IP(192.168.123.187),点击Connect按钮。

三、编写脚本
import uiautomator2 as u2
import time
d = u2.connect_wifi('192.168.123.187')
d.app_start('com.jifen.qukan')
d.xpath('//*[@resource-id="com.jifen.qukan:id/a19"]').click()
d.xpath('//*[@resource-id="com.jifen.qukan:id/ks"]/android.widget.RelativeLayout[3]/android.widget.FrameLayout[1]').click()
while True:
time.sleep(15)
d.swipe(0.462, 0.556,0.452, 0.152,duration=0.1)