获取每个页面的元素,并写入json
获取每个页面的元素,并写入json
想法:如何去记住每个页面的元素,如何实现不同页面的导航,如何从主页面遍历每一个页面的每一个元素
1.创建数据结构存储
2.树状图正好是我们想要的结构体:创建树状图结构体
3.记录每个页面的元素
import json
import os
import uiautomator2 as u2
import xml.etree.ElementTree as ET
def 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:
continue
name = 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="空调")
原文地址:https://blog.csdn.net/huage926/article/details/143020584
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!