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

离线 Chromium 实测 remove()、empty() 与选择器过滤删除

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

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <style>
    .box { height: 100px; width: 300px; border: 1px solid #000; background-color: yellow; }
    .italic { font-style: italic; }
  </style>
</head>
<body>
  <div id="div1" class="box" data-role="removable">
    容器一文本
    <p>容器一中的段落 A</p>
    <p>容器一中的段落 B</p>
  </div>

  <div id="div2" class="box" data-role="emptiable">
    容器二文本
    <p>容器二中的段落 A</p>
    <p>容器二中的段落 B</p>
  </div>

  <div id="list-area">
    <p>普通段落</p>
    <p class="italic">斜体段落一</p>
    <p class="demo">演示段落</p>
    <p class="italic">斜体段落二</p>
  </div>

  <div id="list-compound">
    <p>保留段落</p>
    <p class="italic">斜体项</p>
    <p class="demo">演示项</p>
  </div>

  <script>
    (function () {
      function JQ(els) {
        this.els = Array.from(els);
        this.length = this.els.length;
      }

      JQ.prototype.remove = function (selector) {
        this.els.forEach((el) => {
          if (selector && !el.matches(selector)) return;
          if (el.parentNode) el.parentNode.removeChild(el);
        });
        return this;
      };

      JQ.prototype.empty = function () {
        this.els.forEach((el) => {
          while (el.firstChild) {
            el.removeChild(el.firstChild);
          }
        });
        return this;
      };

      window.$ = function (sel) {
        return new JQ(document.querySelectorAll(sel));
      };
    })();
  </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)
        page = browser.new_page(viewport={"width": 1000, "height": 700})
        page.set_content(HTML_DOC, wait_until="load")

        # Case 1: remove() deletes both the selected element and all its children
        c1 = page.evaluate("""() => {
            const beforeExists = document.querySelector('#div1') !== null;
            const beforeChildren = document.querySelectorAll('#div1 p').length;
            $('#div1').remove();
            return {
                beforeExists,
                beforeChildren,
                afterExists: document.querySelector('#div1') !== null
            };
        }""")
        exp1 = {"beforeExists": True, "beforeChildren": 2, "afterExists": False}
        cases.append(dict(name="remove_element_and_children", expected=exp1, actual=c1, passed=c1 == exp1))

        # Case 2: empty() removes all child nodes/text while keeping the container element itself
        c2 = page.evaluate("""() => {
            $('#div2').empty();
            const el = document.querySelector('#div2');
            const cs = getComputedStyle(el);
            return {
                stillExists: el !== null,
                childNodesLen: el.childNodes.length,
                innerHTML: el.innerHTML,
                roleAttr: el.getAttribute('data-role'),
                bgColor: cs.backgroundColor
            };
        }""")
        exp2 = {
            "stillExists": True,
            "childNodesLen": 0,
            "innerHTML": "",
            "roleAttr": "emptiable",
            "bgColor": "rgb(255, 255, 0)",
        }
        cases.append(dict(name="empty_children_only", expected=exp2, actual=c2, passed=c2 == exp2))

        # Case 3: remove(".italic") filters and removes only matching elements
        c3 = page.evaluate("""() => {
            $('#list-area p').remove('.italic');
            const remaining = Array.from(document.querySelectorAll('#list-area p')).map(e => e.textContent);
            const italicLeft = document.querySelectorAll('#list-area p.italic').length;
            return { remainingCount: remaining.length, remaining, italicLeft };
        }""")
        exp3 = {"remainingCount": 2, "remaining": ["普通段落", "演示段落"], "italicLeft": 0}
        cases.append(dict(name="remove_with_selector_filter", expected=exp3, actual=c3, passed=c3 == exp3))

        # Case 4: remove() accepts multi-selector filter (".italic, .demo")
        c4 = page.evaluate("""() => {
            $('#list-compound p').remove('.italic, .demo');
            const remaining = Array.from(document.querySelectorAll('#list-compound p')).map(e => e.textContent);
            return { remainingCount: remaining.length, remaining };
        }""")
        exp4 = {"remainingCount": 1, "remaining": ["保留段落"]}
        cases.append(dict(name="remove_with_compound_selector", expected=exp4, actual=c4, passed=c4 == exp4))

        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-dom-remove-lab/explore-dom-remove.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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