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

运行元素/#id/.class、12 种进阶选择器与外部脚本拆分离线实验

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

MINI_JQ = r"""
(function (global) {
  function queryJQ(selector) {
    if (selector === ":button") {
      return Array.from(document.querySelectorAll("button, input[type='button']"));
    }
    const mNotAttr = selector.match(/^([a-zA-Z0-9_-]*)\[([a-zA-Z0-9_-]+)!=['"]([^'"]*)['"]\]$/);
    if (mNotAttr) {
      const base = mNotAttr[1] || "*";
      const attr = mNotAttr[2];
      const val = mNotAttr[3];
      return Array.from(document.querySelectorAll(base)).filter(function (el) {
        return el.getAttribute(attr) !== val;
      });
    }
    if (selector.endsWith(":first")) {
      const base = selector.slice(0, -":first".length);
      const list = Array.from(document.querySelectorAll(base));
      return list.length ? [list[0]] : [];
    }
    if (selector.endsWith(":even")) {
      const base = selector.slice(0, -":even".length);
      return Array.from(document.querySelectorAll(base)).filter(function (_, idx) { return idx % 2 === 0; });
    }
    if (selector.endsWith(":odd")) {
      const base = selector.slice(0, -":odd".length);
      return Array.from(document.querySelectorAll(base)).filter(function (_, idx) { return idx % 2 === 1; });
    }
    return Array.from(document.querySelectorAll(selector));
  }

  function JQ(elements) {
    this.elements = elements;
    this.length = elements.length;
  }
  JQ.prototype.each = function (fn) {
    this.elements.forEach(function (el, idx) { fn.call(el, idx, el); });
    return this;
  };
  JQ.prototype.ready = function (fn) {
    if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn);
    else fn();
    return this;
  };
  JQ.prototype.click = function (fn) {
    return this.each(function (_, el) {
      el.addEventListener("click", function (ev) { fn.call(el, ev); });
    });
  };
  JQ.prototype.hide = function () {
    return this.each(function (_, el) { el.style.display = "none"; });
  };
  function $(selector) {
    if (typeof selector === "function") return new JQ([document]).ready(selector);
    if (selector === document || selector instanceof Element) return new JQ([selector]);
    if (typeof selector === "string") return new JQ(queryJQ(selector));
    return new JQ([]);
  }
  $.fn = JQ.prototype;
  $.fn.jquery = "3.7.1-offline-lab";
  global.$ = global.jQuery = $;
})(window);
"""

EXTERNAL_JS = """
$(document).ready(function () {
  window.__externalLoaded = true;
  $("#btn-hide-p").click(function () { $("#sec-el p").hide(); });
  $("#btn-hide-id").click(function () { $("#test").hide(); });
  $("#btn-hide-class").click(function () { $(".test").hide(); });
  $("#btn-self").click(function () { $(this).hide(); });
});
""".strip()

EXTERNAL_DATA_URI = "data:text/javascript;base64," + base64.b64encode(EXTERNAL_JS.encode("utf-8")).decode("ascii")

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery 选择器离线实验</title>
  <script>{MINI_JQ}</script>
  <script id="ext-fn-script" src="{EXTERNAL_DATA_URI}"></script>
</head>
<body>
  <section id="sec-el">
    <p id="ep1">元素段落 1</p>
    <p id="ep2">元素段落 2</p>
    <div id="ed1">保留 div</div>
    <button id="btn-hide-p" type="button">隐藏 p</button>
  </section>

  <section id="sec-id">
    <p id="test">唯一 ID 段落</p>
    <p id="keep-id">普通段落</p>
    <button id="btn-hide-id" type="button">隐藏 #test</button>
  </section>

  <section id="sec-cls">
    <h3 id="ch1" class="test">标题带 .test</h3>
    <p id="cp1" class="test">段落带 .test</p>
    <p id="cp2">无 .test 段落</p>
    <button id="btn-hide-class" type="button">隐藏 .test</button>
  </section>

  <section id="sec-more">
    <button id="btn-self" type="button">隐藏自身</button>
    <p id="intro-p" class="intro">带 intro 的段落</p>
    <div id="intro-div" class="intro">带 intro 的 div</div>
    <ul id="ul1">
      <li id="u1l1">L1-1</li>
      <li id="u1l2">L1-2</li>
    </ul>
    <ul id="ul2">
      <li id="u2l1">L2-1</li>
      <li id="u2l2">L2-2</li>
    </ul>
    <a id="a-blank" href="#b" target="_blank">新窗口链接</a>
    <a id="a-self" href="#s" target="_self">当前窗口链接</a>
    <a id="a-no-target" href="#n">无 target 链接</a>
    <a id="a-no-href">无 href 锚点</a>
    <input id="in-btn" type="button" value="输入按钮">
    <input id="in-txt" type="text" value="文本框">
    <table id="zebra">
      <tr id="r0"><td>0</td></tr>
      <tr id="r1"><td>1</td></tr>
      <tr id="r2"><td>2</td></tr>
      <tr id="r3"><td>3</td></tr>
      <tr id="r4"><td>4</td></tr>
    </table>
  </section>
</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 pw:
        browser = launch_browser(pw)
        try:
            page = browser.new_page()
            page.set_content(HTML_DOC, wait_until="load")

            # Case 1: Element, #id, and .class selectors via real button clicks
            page.locator("#btn-hide-p").click()
            page.locator("#btn-hide-id").click()
            page.locator("#btn-hide-class").click()
            act1 = page.evaluate(
                """() => ({
                    el_panel: ["ep1", "ep2", "ed1"].map(id => getComputedStyle(document.getElementById(id)).display),
                    id_panel: ["test", "keep-id"].map(id => getComputedStyle(document.getElementById(id)).display),
                    cls_panel: ["ch1", "cp1", "cp2"].map(id => getComputedStyle(document.getElementById(id)).display)
                })"""
            )
            exp1 = {
                "el_panel": ["none", "none", "block"],
                "id_panel": ["none", "block"],
                "cls_panel": ["none", "none", "block"],
            }
            cases.append(dict(name="element_id_class_selectors", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: $("*"), $(this), $("p.intro"), $("p:first"), $("ul li:first") vs $("ul li:first-child")
            page.locator("#btn-self").click()
            act2 = page.evaluate(
                """() => ({
                    star_gt_20: $("*").length > 20,
                    this_hidden: getComputedStyle(document.getElementById("btn-self")).display,
                    p_intro: $("p.intro").elements.map(e => e.id),
                    p_first: $("p:first").elements.map(e => e.id),
                    ul_li_first: $("ul li:first").elements.map(e => e.id),
                    ul_li_first_child: $("ul li:first-child").elements.map(e => e.id)
                })"""
            )
            exp2 = {
                "star_gt_20": True,
                "this_hidden": "none",
                "p_intro": ["intro-p"],
                "p_first": ["ep1"],
                "ul_li_first": ["u1l1"],
                "ul_li_first_child": ["u1l1", "u2l1"],
            }
            cases.append(dict(name="structural_and_this_selectors", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: Attribute selectors, :button, tr:even, tr:odd
            act3 = page.evaluate(
                """() => ({
                    href_ids: $("[href]").elements.map(e => e.id),
                    target_blank: $("a[target='_blank']").elements.map(e => e.id),
                    target_not_blank: $("a[target!='_blank']").elements.map(e => e.id),
                    button_ids: $(":button").elements.map(e => e.id),
                    tr_even: $("tr:even").elements.map(e => e.id),
                    tr_odd: $("tr:odd").elements.map(e => e.id)
                })"""
            )
            exp3 = {
                "href_ids": ["a-blank", "a-self", "a-no-target"],
                "target_blank": ["a-blank"],
                "target_not_blank": ["a-self", "a-no-target", "a-no-href"],
                "button_ids": ["btn-hide-p", "btn-hide-id", "btn-hide-class", "btn-self", "in-btn"],
                "tr_even": ["r0", "r2", "r4"],
                "tr_odd": ["r1", "r3"],
            }
            cases.append(dict(name="attribute_button_zebra_selectors", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: External script separation & load order
            act4 = page.evaluate(
                """() => ({
                    external_loaded: window.__externalLoaded === true,
                    has_src_attr: document.getElementById("ext-fn-script").hasAttribute("src")
                })"""
            )
            exp4 = {"external_loaded": True, "has_src_attr": True}
            cases.append(dict(name="external_js_separation", passed=(act4 == exp4), expected=exp4, actual=act4))
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


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

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

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

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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