python获取安卓Hierarchy并解析

python获取安卓Hierarchy并解析

借助 uiautomator 命令 dump 当前页面的 ui hierarchy 信息
完整的 uiautomator 命令类似:

adb shell uiautomator dump [--compressed] [file]

解析需要使用:import xml.etree.ElementTree as ET
完整代码如下:

import uiautomator2 as u2
import subprocess
import xml.etree.ElementTree as ET
def get_hierarchy():
    result = subprocess.run(['adb', 'shell', 'uiautomator', 'dump'], stdout=subprocess.PIPE)
    with open('hierarchy.xml', 'wb') as f:
        f.write(result.stdout)
    print("Hierarchy dumped to hierarchy.xml")
def u2_get_hierarchy():
	# 获取设备实例
	device = u2.connect()
	hierarchy = device.dump_hierarchy()
	print(hierarchy)

def parse_hierarchy(xml_file):
    tree = ET.parse(xml_file)
    root = tree.getroot()
    # 遍历视图层次结构并打印视图信息
    # 遍历 XML 树中的元素
    for element in root.iter():
        # 获取元素的文本内容
        text = element.text

        # 获取元素的 resource-id 属性
        resource_id = element.get('resource-id')

        # 获取元素的 class 属性
        class_name = element.get('class')

        # 获取元素的 package 属性
        package_name = element.get('package')

        # 获取元素的 bounds 属性
        bounds = element.get('bounds')

        # 打印结果或进行其他操作
        print("Text:", text)
        print("Resource ID:", resource_id)
        print("Class:", class_name)
        print("Package:", package_name)
        print("Bounds:", bounds)

#
# get_hierarchy()
# 调用函数并传入XML文件路径
parse_hierarchy("1.xml")

嘻嘻,这样就可以愉快的获取到安卓的的树结构了,玩转自动化,小小元素拿捏

猜你喜欢

转载自blog.csdn.net/huage926/article/details/134015392
今日推荐