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

在离线 Chromium 中实测 first()、last()、eq()、filter() 与 not() 五种集合过滤方法

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

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>jQuery Filtering Lab</title></head>
<body>
  <div id="d1" style="border: 1px solid black;">
    <p id="p0" class="intro">第一个 div 的第一段</p>
    <p id="p1" class="url">第一个 div 的第二段 (class="url")</p>
  </div>
  <div id="d2" style="border: 1px solid black;">
    <p id="p2" class="note">第二个 div 的第一段</p>
    <p id="p3" class="url">第二个 div 的第二段 (class="url")</p>
  </div>
  <script>
    (function (global) {
      function wrap(nodes) {
        const list = Array.from(nodes);
        return {
          nodes: list,
          length: list.length,
          ids() {
            return list.map(el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
          },
          css(prop, val) {
            for (const el of list) el.style[prop] = val;
            return this;
          },
          first() {
            return wrap(list.length ? [list[0]] : []);
          },
          last() {
            return wrap(list.length ? [list[list.length - 1]] : []);
          },
          eq(index) {
            const idx = index < 0 ? list.length + index : index;
            return wrap(idx >= 0 && idx < list.length ? [list[idx]] : []);
          },
          filter(criteria) {
            if (typeof criteria === 'function') {
              return wrap(list.filter((el, i) => criteria.call(el, i, el)));
            }
            return wrap(list.filter(el => el.matches(criteria)));
          },
          not(criteria) {
            if (typeof criteria === 'function') {
              return wrap(list.filter((el, i) => !criteria.call(el, i, el)));
            }
            return wrap(list.filter(el => !el.matches(criteria)));
          }
        };
      }
      global.$ = function (arg) {
        if (arg === document) return { ready(fn) { fn(); } };
        if (typeof arg === 'string') return wrap(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 = $("div p").first().css("backgroundColor", "yellow");
                return {
                    matched: res.ids(),
                    p0_bg: getComputedStyle(document.getElementById("p0")).backgroundColor,
                    p1_bg: getComputedStyle(document.getElementById("p1")).backgroundColor
                };
            }""")
            exp1 = {
                "matched": ["p#p0"],
                "p0_bg": "rgb(255, 255, 0)",
                "p1_bg": "rgba(0, 0, 0, 0)",
            }
            cases.append({"name": "first_matched_element", "passed": c1 == exp1, "expected": exp1, "actual": c1})

            c2 = page.evaluate("""() => {
                const res = $("div p").last().css("backgroundColor", "cyan");
                return {
                    matched: res.ids(),
                    p3_bg: getComputedStyle(document.getElementById("p3")).backgroundColor
                };
            }""")
            exp2 = {
                "matched": ["p#p3"],
                "p3_bg": "rgb(0, 255, 255)",
            }
            cases.append({"name": "last_matched_element", "passed": c2 == exp2, "expected": exp2, "actual": c2})

            c3 = page.evaluate("""() => ({
                eq_0: $("p").eq(0).ids(),
                eq_1: $("p").eq(1).ids(),
                eq_neg1: $("p").eq(-1).ids(),
                eq_out_of_range: $("p").eq(10).ids()
            })""")
            exp3 = {
                "eq_0": ["p#p0"],
                "eq_1": ["p#p1"],
                "eq_neg1": ["p#p3"],
                "eq_out_of_range": [],
            }
            cases.append({"name": "eq_zero_based_and_negative_index", "passed": c3 == exp3, "expected": exp3, "actual": c3})

            c4 = page.evaluate("""() => ({
                filter_url: $("p").filter(".url").ids(),
                filter_even_index: $("p").filter((i) => i % 2 === 0).ids()
            })""")
            exp4 = {
                "filter_url": ["p#p1", "p#p3"],
                "filter_even_index": ["p#p0", "p#p2"],
            }
            cases.append({"name": "filter_matching_criteria", "passed": c4 == exp4, "expected": exp4, "actual": c4})

            c5 = page.evaluate("""() => {
                const kept = $("p").filter(".url").ids();
                const excluded = $("p").not(".url").ids();
                return {
                    not_url: excluded,
                    complement_count_matches_total: kept.length + excluded.length === $("p").length,
                    disjoint: kept.every(id => !excluded.includes(id))
                };
            }""")
            exp5 = {
                "not_url": ["p#p0", "p#p2"],
                "complement_count_matches_total": True,
                "disjoint": True,
            }
            cases.append({"name": "not_excluding_criteria", "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-filtering-lab/explore-traversing-filtering.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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