android 原生 app 爬虫 uiautomator
安装环境 JRE
# mac
brew update
brew cask install java
# 或
brew tap caskroom/versions
brew cask instal java8
# ubuntu
apt-get update
apt-get install default-jre
安装 android sdk
到网页的最底部, 在 "Command line tools only" 下载系统对应的 sdk
bin/sdkmanager "platform-tools"
# 或者安装代理
bin/sdkmanager "platform-tools" --proxy=http --proxy-host=代理IP --proxy-port=代理端口
设置环境变量
platform-tools
tools
# 添加目录里对应的文件夹
设置开发者模式
打开手机的开发者模式, usb 调试, usb 安装
调试
uiautomatorviewer
# 会打开一个窗口, 点击左上角的手机图标, 就会在电脑上看到手机界面
使用 python 调试手机
使用 python 调试手机, uiautomatorviewer 不能同时运行, 利用"一键优化" 或 关机重启, 杀掉 python 安装的两个进程
pip install uiautomator
>>> from uiautomator import Device
>>> devide = Device()
>>> print(device.dump())
# 第一次运行, 会在手机上安装两个没有图标的程序, 点击允许安装
打开微信
>>>from uiautomator import Device
>>>device = Device()
>>>device(text="微信").click()
# 显示所有连接电脑的手机
adb device -l
>>>device = Dvice('串号')
from uiautomator import Device
device = Device()
print(device.dump()) # 以 xml 形式输入当前手机屏幕的布局信息
device(packageName='com.android.systemui')
device(className='android.widget.FrameLayout')
device(resourceId='com.android.systemui:id/clock')
device(text='短信')
device(index='3', resourceId='com.android.systemui:id/mobile_combo')
获得屏幕文字
device.dump()
title = device(resourceId='id名').text
# 如果有多个
title = device(resourceId='id名')
for t in title:
print(t.text)
滚动屏幕
device(scrollable=True)
# 上滚一屏
device(scrollable=True).scroll.vert.forward()
# 下滚一屏
device(scrollable=True).scroll.vert.backward()
# 右滚一屏
device(scrollable=True).scroll.horiz.forward()
# 左滚一屏
device(scrollable=True).scroll.horiz.backward()
滑动屏幕
# 起始x坐标,
device.swipe(400, 600, 0, 600)
点击屏幕
所有的坐标位置, 可以在 uiautomatorviewer
里显示
# 短按, 长按
device(text="微信").click()
device(text="微信").long_click()
device.click(230, 567)
device.long_click(230, 567)
输入文字
device(resourceId="ID").set_text("输入的文字")
判断元素是否存在
input_box = device(resourceId='ID')
if input_box.exists:
input_box.set_text('输入文字')
else:
print('不存在')
等待加载
input_box = device(resourceId='ID')
if input_box.wait.exists(timeout=20000):
input_box.set_text('输入文字')
else:
print('不存在')
点亮屏幕
# 点亮屏幕
device.wakeup()
# 关闭屏幕
device.sleep()
if device.screen == 'on':
print('当前屏幕为点亮状态')
elif device.screen == 'off':
print('当前屏幕为关闭状态')
操作实体键
power 电源键
back 返回
menu 菜单键
volume_up 音量增大
volume_down 音量减小
home 返回左面
device.press.power()
device.press.volume_up()
watcher
满足3个条件, 激活 watcher
找不到元素, 即将报错
当屏幕上出现文本 "文字1"
当屏幕上出现文本 "文字2"
from uiautomator import Device
device = Device()
device.watcher('注册 watcher 名字').when(text="文字1").when(text="文字2").press.back()
...
# 下面为执行的代码