termux+uiautomator2自动化

termux+uiautomator2自动化

termux环境设置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
apt install -y clang libxml2 libxslt python-pip libjpeg-turbo zlib android-tools 
pip install cython lxml
pip install --pre uiautomator2
python -m uiautomator2 init		# 前提是USB调试打开的情况下已经连接无线调试或者USB连接电脑
adb connect 192.168.3.175:5555
{
  echo 'import uiautomator2 as u2'
  echo 'dev = u2.connect("192.168.3.175")'
  echo 'print (dev.info)'
} > testdemo.py
python testdemo.py

给QQ好友点赞

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import uiautomator2 as u2

def main():
    u = u2.connect('192.168.3.193')    
    
    # 输入设备
    # print(u.info)

    # QQ好友点赞
    u.app_start('com.tencent.mobileqq')    
    u.click(88,173)
    u(text='夜闹').click()
    u.click(975,695)
    for i in range(10):
        u.click(1018,1157)

if __name__ == '__main__':
    main()

元素定位

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import uiautomator2 as u2

def main():
    u = u2.connect('192.168.3.193')    
    
    # 元素定位
    xml = u.dump_hierarchy()
    # print(xml)
    # 保存到文件(方便分析)
    with open("ui_dump.xml", "w", encoding="utf-8") as f:
        f.write(xml)

if __name__ == '__main__':
    main()

使用 weditor 可视化查看元素

1
2
3
4
# pip install weditor setuptools
pip install setuptools -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -e weditor -i https://pypi.tuna.tsinghua.edu.cn/simple
python -m weditor

浏览器会自动打开 http://localhost:17310,选择设备后即可 实时查看界面元素(类似 Appium Inspector)。