如何在 python 中使用 uiautpmator2 读取任何 Android 应用程序视图/布局的内容描述

问题描述 投票:0回答:2

我正在使用 uiautomator2 和 python 为 Android 应用程序编写 ui 自动化。如何使用 python 中的 uiautpmator2 读取任何 Android 应用程序视图/布局的内容描述?

我已经尝试过下面的代码,但我不知道如何阅读内容描述

import uiautomator2 as u2
import subprocess 
adb_device = subprocess.run('adb devices', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

amc = u2.connect(adb_device.stdout.split('\n')[1][:-7]) 

amc(text="",resourceId="com.company.le.mesh.meshapp:id/toolbar_layout",className="android.widget.FrameLayout",contentDesc='New Room').exists()

我无法阅读 Android 应用布局/视图的内容描述。相反,出现以下错误:

Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "C:\Users\jhaavinash\AppData\Local\Programs\Python\Python38-32\lib\site-packages\uiautomator2\__init__.py", line 1312, in __call__
    return UiObject(self, Selector(**kwargs))   File "C:\Users\jhaavinash\AppData\Local\Programs\Python\Python38-32\lib\site-packages\uiautomator2\_selector.py", line 52, in __init__
    self[k] = kwargs[k]   File "C:\Users\jhaavinash\AppData\Local\Programs\Python\Python38-32\lib\site-packages\uiautomator2\_selector.py", line 73, in __setitem__
    raise ReferenceError("%s is not allowed." % k) ReferenceError: contentDesc is not allowed.
python ui-automation
2个回答
0
投票

uiautomator 2 的 info 关键字在这里有所帮助。 下面的代码帮助我阅读布局的内容描述。

amc(resourceId='com.cypress.le.mesh.meshapp:id/toolbar_layout').info['contentDescription']

0
投票

你可以使用

print(amc.xpath("//[@content-desc='new room']").exists)

要从“ViewGroup”和“TextView”类中的 content-desc 获取所有值:

for el in amc.xpath("//android.widget.TextView").all():
    print("content-desc:", el.info['contentDescription'])

for el in amc.xpath("//android.view.ViewGroup").all():
    print("content-desc:", el.info['contentDescription'])

Github源码

© www.soinside.com 2019 - 2024. All rights reserved.