获取每个页面的元素,并写入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="空调")