From 83ea129d8c59dcf687a0eb593f55208eec713ffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8D=8E=E5=87=AF?= <13959713+haiyang0726@user.noreply.gitee.com> Date: Fri, 12 Jan 2024 01:46:55 +0000 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0ele.tree()=20=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E7=94=A8=E9=80=94=EF=BC=9A=E6=89=93=E5=8D=B0?= =?UTF-8?q?=E5=BD=93=E5=89=8D=E5=85=83=E7=B4=A0=E7=9A=84=E5=AD=90=E5=85=83?= =?UTF-8?q?=E7=B4=A0=E7=BB=93=E6=9E=84=E6=A0=91=EF=BC=8C=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E5=B1=95=E5=BC=80=E5=B1=82=E6=95=B0=E6=98=AF5=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘华凯 <13959713+haiyang0726@user.noreply.gitee.com> --- DrissionPage/_elements/chromium_element.py | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/DrissionPage/_elements/chromium_element.py b/DrissionPage/_elements/chromium_element.py index 642121d..1eb34e9 100644 --- a/DrissionPage/_elements/chromium_element.py +++ b/DrissionPage/_elements/chromium_element.py @@ -9,6 +9,7 @@ from os.path import basename, sep from pathlib import Path from re import search from time import perf_counter, sleep +from colorama import Fore, init from DataRecorder.tools import get_usable_path @@ -122,6 +123,30 @@ class ChromiumElement(DrissionElement): def text(self): """返回元素内所有文本,文本已格式化""" return get_ele_txt(make_session_ele(self.html)) + + def tree(self): + """打印当前元素的子元素结构树,默认展开层数是5层""" + init() + self.__tree(ele=self) + + def __tree(self,ele, layer=5, last_one=False, body=''): + list_ele = ele.children(timeout=0.1) + length = len(list_ele) + body_unit = ' ' if last_one else '│ ' + tail = '├───' + new_body = body + body_unit + + if length > 0 and layer >= 1: + new_last_one = False + for i in range(length): + if i == length - 1: + tail = '└───' + new_last_one = True + e = list_ele[i] + + print(f'{Fore.BLUE}{new_body}{tail}{Fore.CYAN}{i}<{e.tag}> {Fore.RESET}{e.attrs}') + + self.__tree(e, layer - 1, new_last_one, new_body) @property def raw_text(self):