蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在离线 Chromium 中实测四层 DOM 家族树的向上、向下、水平与链式遍历

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-traversing.py
explore-traversing.py176 行
"""Offline Playwright Chromium lab for jQuery Chapter 21 (traversing)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>jQuery Traversing Tree Lab</title></head>
<body>
  <div id="root-div" class="tree-root">
    <ul id="main-ul">
      <li id="li-left"><span id="span-1">左子项A</span><span id="span-2">左子项B</span></li>
      <li id="li-right"><b id="b-1">右子项粗体</b></li>
    </ul>
  </div>
  <script>
    (function (global) {
      function unique(arr) {
        const out = [];
        for (const el of arr) {
          if (el && el.nodeType === 1 && !out.includes(el)) out.push(el);
        }
        return out;
      }
      function wrap(nodes) {
        const list = unique(nodes);
        return {
          nodes: list,
          length: list.length,
          ids() {
            return list.map(el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
          },
          parent(sel) {
            const res = [];
            for (const el of list) {
              const p = el.parentElement;
              if (p && (!sel || p.matches(sel))) res.push(p);
            }
            return wrap(res);
          },
          parents(sel) {
            const res = [];
            for (const el of list) {
              let cur = el.parentElement;
              while (cur) {
                if (!sel || cur.matches(sel)) res.push(cur);
                cur = cur.parentElement;
              }
            }
            return wrap(res);
          },
          children(sel) {
            const res = [];
            for (const el of list) {
              for (const ch of Array.from(el.children)) {
                if (!sel || ch.matches(sel)) res.push(ch);
              }
            }
            return wrap(res);
          },
          find(sel) {
            const res = [];
            for (const el of list) {
              for (const d of Array.from(el.querySelectorAll(sel))) res.push(d);
            }
            return wrap(res);
          },
          siblings(sel) {
            const res = [];
            for (const el of list) {
              if (!el.parentElement) continue;
              for (const ch of Array.from(el.parentElement.children)) {
                if (ch !== el && (!sel || ch.matches(sel))) res.push(ch);
              }
            }
            return wrap(res);
          }
        };
      }
      global.$ = function (selector) {
        if (typeof selector === 'string') {
          return wrap(Array.from(document.querySelectorAll(selector)));
        }
        if (selector && selector.nodeType === 1) return wrap([selector]);
        return wrap([]);
      };
    })(window);
  </script>
</body>
</html>
"""


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page(viewport={"width": 1000, "height": 700})
            page.set_content(HTML_DOC)

            c1 = page.evaluate("""() => ({
                span1_parent: $("#span-1").parent().ids(),
                span1_ancestors: $("#span-1").parents().ids(),
                b1_parent: $("#b-1").parent().ids(),
                b1_ancestors: $("#b-1").parents().ids(),
                ul_parent: $("#main-ul").parent().ids()
            })""")
            exp1 = {
                "span1_parent": ["li#li-left"],
                "span1_ancestors": ["li#li-left", "ul#main-ul", "div#root-div", "body", "html"],
                "b1_parent": ["li#li-right"],
                "b1_ancestors": ["li#li-right", "ul#main-ul", "div#root-div", "body", "html"],
                "ul_parent": ["div#root-div"],
            }
            cases.append({"name": "dom_family_tree_ancestors", "passed": c1 == exp1, "expected": exp1, "actual": c1})

            c2 = page.evaluate("""() => ({
                div_children: $("#root-div").children().ids(),
                div_all_descendants: $("#root-div").find("*").ids(),
                ul_children: $("#main-ul").children().ids(),
                li_left_children: $("#li-left").children().ids(),
                li_right_children: $("#li-right").children().ids()
            })""")
            exp2 = {
                "div_children": ["ul#main-ul"],
                "div_all_descendants": ["ul#main-ul", "li#li-left", "span#span-1", "span#span-2", "li#li-right", "b#b-1"],
                "ul_children": ["li#li-left", "li#li-right"],
                "li_left_children": ["span#span-1", "span#span-2"],
                "li_right_children": ["b#b-1"],
            }
            cases.append({"name": "dom_family_tree_descendants", "passed": c2 == exp2, "expected": exp2, "actual": c2})

            c3 = page.evaluate("""() => ({
                li_left_siblings: $("#li-left").siblings().ids(),
                li_right_siblings: $("#li-right").siblings().ids(),
                span1_siblings: $("#span-1").siblings().ids(),
                b1_siblings: $("#b-1").siblings().ids(),
                same_parent_for_li: $("#li-left").parent().ids()[0] === $("#li-right").parent().ids()[0]
            })""")
            exp3 = {
                "li_left_siblings": ["li#li-right"],
                "li_right_siblings": ["li#li-left"],
                "span1_siblings": ["span#span-2"],
                "b1_siblings": [],
                "same_parent_for_li": True,
            }
            cases.append({"name": "dom_family_tree_siblings", "passed": c3 == exp3, "expected": exp3, "actual": c3})

            c4 = page.evaluate("""() => ({
                span1_to_right_b: $("#span-1").parent().siblings().children().ids(),
                b1_up_to_ul_down_spans: $("#b-1").parents("ul").find("span").ids(),
                tree_node_count_under_div: $("#root-div").find("*").length,
                external_cdn_scripts: document.querySelectorAll("script[src]").length
            })""")
            exp4 = {
                "span1_to_right_b": ["b#b-1"],
                "b1_up_to_ul_down_spans": ["span#span-1", "span#span-2"],
                "tree_node_count_under_div": 6,
                "external_cdn_scripts": 0,
            }
            cases.append({"name": "chained_tree_traversal_directions", "passed": c4 == exp4, "expected": exp4, "actual": c4})
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jquery-traversing-lab/explore-traversing.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-traversing.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a910.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习