欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > 获取每个页面的元素,并写入json

获取每个页面的元素,并写入json

2024/10/23 23:27:45 来源:https://blog.csdn.net/huage926/article/details/143020584  浏览:    关键词:获取每个页面的元素,并写入json

获取每个页面的元素,并写入json

想法:如何去记住每个页面的元素,如何实现不同页面的导航,如何从主页面遍历每一个页面的每一个元素
1.创建数据结构存储
2.树状图正好是我们想要的结构体:创建树状图结构体
3.记录每个页面的元素

import json
import osimport uiautomator2 as u2
import xml.etree.ElementTree as ETdef u2_get_hierarchy(filename):# 获取设备实例id_xpath, class_xpath, text_xpath, class_and_text_xpath = "", "", "", ""mapping = {}device = u2.connect()hierarchy = device.dump_hierarchy()root = ET.fromstring(hierarchy)# 遍历视图层次结构并打印视图信息for element in root.iter():# print( element.attrib)# 获取元素的文本内容text = element.get('text')# 获取元素的 resource-id 属性resource_id = element.get('resource-id')# 获取元素的 class 属性class_name = element.get('class')if resource_id and class_name:id_xpath = f"//*[@resource-id='{resource_id}']"class_xpath = f"//@class='{class_name}'"if text and class_name:text_xpath = f"//*[@text='{text}']"class_and_text_xpath = f"//'{class_name}'[@text='{text}']"if not text and not resource_id:continuename = text if text else resource_id.split("/")[-1]mapping.update({name: {"text": text,"resource_id": resource_id,"class_name": class_name,"id_xpath": id_xpath,"class_xpath": class_xpath,"text_xpath": text_xpath,"class_and_text_xpath": class_and_text_xpath}})filename = f"{filename}.json"if not os.path.exists(filename):with open(filename, "w",encoding='utf-8') as fp:json.dump(mapping, fp,ensure_ascii=False, indent=4)else:with open(filename, "r", encoding='utf-8') as fp:data = json.load(fp)data.update(mapping)with open(filename, "w", encoding='utf-8') as f:json.dump(data, f, ensure_ascii=False, indent=4)if __name__ == '__main__':u2_get_hierarchy(filename="空调")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com