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

在离线 Chromium 中全量实测 siblings() 及 next/prev 全套六种水平遍历方法

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

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery Siblings Lab</title>
  <style>
    .siblings * { display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 8px; }
  </style>
</head>
<body class="siblings">
  <div id="sib-box">div (父元素)
    <p id="p-before">p (前同胞)</p>
    <span id="sp-before">span (前同胞)</span>
    <h2 id="anchor-h2">h2 (当前元素)</h2>
    <h3 id="h3-el">h3</h3>
    <p id="p-after">p (后同胞)</p>
    <h4 id="h4-el">h4</h4>
    <h5 id="h5-el">h5</h5>
    <h6 id="h6-el">h6</h6>
    <p id="p-tail">p (末尾同胞)</p>
  </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 : ''));
          },
          css(props) {
            for (const el of list) {
              for (const [k, v] of Object.entries(props)) el.style[k] = v;
            }
            return this;
          },
          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);
          },
          next(sel) {
            const res = [];
            for (const el of list) {
              const n = el.nextElementSibling;
              if (n && (!sel || n.matches(sel))) res.push(n);
            }
            return wrap(res);
          },
          nextAll(sel) {
            const res = [];
            for (const el of list) {
              let cur = el.nextElementSibling;
              while (cur) {
                if (!sel || cur.matches(sel)) res.push(cur);
                cur = cur.nextElementSibling;
              }
            }
            return wrap(res);
          },
          nextUntil(stopSel, filterSel) {
            const res = [];
            for (const el of list) {
              let cur = el.nextElementSibling;
              while (cur) {
                if (stopSel && cur.matches(stopSel)) break;
                if (!filterSel || cur.matches(filterSel)) res.push(cur);
                cur = cur.nextElementSibling;
              }
            }
            return wrap(res);
          },
          prev(sel) {
            const res = [];
            for (const el of list) {
              const p = el.previousElementSibling;
              if (p && (!sel || p.matches(sel))) res.push(p);
            }
            return wrap(res);
          },
          prevAll(sel) {
            const res = [];
            for (const el of list) {
              let cur = el.previousElementSibling;
              while (cur) {
                if (!sel || cur.matches(sel)) res.push(cur);
                cur = cur.previousElementSibling;
              }
            }
            return wrap(res);
          },
          prevUntil(stopSel, filterSel) {
            const res = [];
            for (const el of list) {
              let cur = el.previousElementSibling;
              while (cur) {
                if (stopSel && cur.matches(stopSel)) break;
                if (!filterSel || cur.matches(filterSel)) res.push(cur);
                cur = cur.previousElementSibling;
              }
            }
            return wrap(res);
          }
        };
      }
      global.$ = function (arg) {
        if (arg === document) return { ready(fn) { fn(); } };
        if (typeof arg === 'string') return wrap(Array.from(document.querySelectorAll(arg)));
        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("""() => {
                const res = $("h2").siblings();
                return {
                    all_siblings: res.ids(),
                    count: res.length,
                    excludes_self: !res.ids().includes("h2#anchor-h2")
                };
            }""")
            exp1 = {
                "all_siblings": [
                    "p#p-before", "span#sp-before", "h3#h3-el", "p#p-after",
                    "h4#h4-el", "h5#h5-el", "h6#h6-el", "p#p-tail",
                ],
                "count": 8,
                "excludes_self": True,
            }
            cases.append({"name": "siblings_all_excluding_self", "passed": c1 == exp1, "expected": exp1, "actual": c1})

            c2 = page.evaluate("""() => {
                const res = $("h2").siblings("p").css({ color: "red", border: "2px solid red" });
                return {
                    p_siblings: res.ids(),
                    p_after_color: getComputedStyle(document.getElementById("p-after")).color,
                    h3_color: getComputedStyle(document.getElementById("h3-el")).color
                };
            }""")
            exp2 = {
                "p_siblings": ["p#p-before", "p#p-after", "p#p-tail"],
                "p_after_color": "rgb(255, 0, 0)",
                "h3_color": "rgb(211, 211, 211)",
            }
            cases.append({"name": "siblings_filtered_by_selector", "passed": c2 == exp2, "expected": exp2, "actual": c2})

            c3 = page.evaluate("""() => ({
                h2_next: $("h2").next().ids(),
                h2_next_count: $("h2").next().length,
                tail_next: $("#p-tail").next().ids()
            })""")
            exp3 = {
                "h2_next": ["h3#h3-el"],
                "h2_next_count": 1,
                "tail_next": [],
            }
            cases.append({"name": "next_single_immediate_sibling", "passed": c3 == exp3, "expected": exp3, "actual": c3})

            c4 = page.evaluate("""() => ({
                h2_next_all: $("h2").nextAll().ids(),
                h2_next_until_h6: $("h2").nextUntil("h6").ids(),
                h2_next_until_h6_only_p: $("h2").nextUntil("h6", "p").ids()
            })""")
            exp4 = {
                "h2_next_all": ["h3#h3-el", "p#p-after", "h4#h4-el", "h5#h5-el", "h6#h6-el", "p#p-tail"],
                "h2_next_until_h6": ["h3#h3-el", "p#p-after", "h4#h4-el", "h5#h5-el"],
                "h2_next_until_h6_only_p": ["p#p-after"],
            }
            cases.append({"name": "next_all_and_next_until", "passed": c4 == exp4, "expected": exp4, "actual": c4})

            c5 = page.evaluate("""() => ({
                h2_prev: $("h2").prev().ids(),
                h2_prev_all: $("h2").prevAll().ids(),
                h6_prev_until_h2: $("#h6-el").prevUntil("h2").ids(),
                p_before_prev: $("#p-before").prev().ids()
            })""")
            exp5 = {
                "h2_prev": ["span#sp-before"],
                "h2_prev_all": ["span#sp-before", "p#p-before"],
                "h6_prev_until_h2": ["h5#h5-el", "h4#h4-el", "p#p-after", "h3#h3-el"],
                "p_before_prev": [],
            }
            cases.append({"name": "prev_prev_all_and_prev_until", "passed": c5 == exp5, "expected": exp5, "actual": c5})
        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-siblings-lab/explore-traversing-siblings.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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