• python获取安卓Hierarchy并解析


    python获取安卓Hierarchy并解析

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

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

    解析需要使用: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")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

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

  • 相关阅读:
    技术创新驱动销售 植宗山茶油首登排行榜
    Python最简单的sklearn库安装教程
    芯片工程师求职题目之CPU篇(4)
    (2022版)一套教程搞定k8s安装到实战 | 生产环境关键性配置
    Python 异步网络编程实战
    【ubuntu】nfs服务搭建
    【C++】智能指针
    react-redux基本使用
    Docker学习(六):Docker Compose和Docker Stack区别
    基于Python实现并测试Modularity算法
  • 原文地址:https://blog.csdn.net/huage926/article/details/134015392