本文共 1895 字,大约阅读时间需要 6 分钟。
分析了一个应用的文本抓取需求,最终选择了基于Android的ADB工具进行操作。由于直接操作安卓设备加密内容较为困难,选择了ADB作为工具主要是因为:
使用ADB进行文本捕获:
adb shell input text "要查询的文本内容"
adb shell uiautomator dump /sdcard/ui.xml
adb pull /sdcard/ui.xml ui.xml
引入uiautomator2进行优化:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple uiautomator2python -m uiautomator2 init
d = u2.connect()print(d.xpath('//*').all())def print TextViews(): for view in d.xpath('//android.widget.TextView').all(): print(f"【{i:04}】{view.text}")printTextviewAll()
解决ADB常态崩溃问题:
for _ in range(3): os.system(f"taskkill /F /IM nox_adb.exe") time.sleep(2)while True: try: subprocess.check_call(["nox_adb.exe", "connect", "127.0.0.1:62001"]) d = u2.connect() break except Exception as e: print(f"{e} 请稍等...") time.sleep(10)
对比UISelector与XPath:
功能 | UISelector示例 | XPath示例 |
---|---|---|
按下文本 | d(text='立即开户') | d.xpath("立即开户") |
正则匹配文本 | d(textMatches='正则语句') | d.xpath("//*[re:match(@text, '^正则语句')]") |
文本内容 | d(text='文本') | d.xpath("=@text, '文本'") |
描述内容 | d(description='文本') | d.xpath("=@content-desc, '文本'") |
资源ID | d(resourceId='文本') | d.xpath("=@resource-id, '文本'") |
空文本 | d(text='') | d.xpath("=@text, ''") |
获取Info | d.info | d.xpath(...).info |
获取Bounds | d.bounds() | d.xpath(...).bounds() |
实际应用中的自动化工具:
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysdriver = webdriver.Chrome()driver.get('https://www.example.com')elem = driver.find_element_by_xpath('//button[text()="登录"]').send_keys(Keys.ENTER)driver.quit()
总体体会:
转载地址:http://cesyk.baihongyu.com/