"""Offline Playwright Chromium lab for jQuery Chapter 2 (intro)."""
import json
from playwright.sync_api import sync_playwright
MINI_JQ = r"""
(function (global) {
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.text = function (val) {
if (val === undefined) return this.elements[0] ? this.elements[0].textContent : "";
return this.each(function (_, el) { el.textContent = val; });
};
JQ.prototype.append = function (html) {
return this.each(function (_, el) { el.insertAdjacentHTML("beforeend", html); });
};
JQ.prototype.css = function (prop, val) {
if (val === undefined) return this.elements[0] ? getComputedStyle(this.elements[0])[prop] : undefined;
return this.each(function (_, el) { el.style[prop] = val; });
};
JQ.prototype.click = function (fn) {
return this.each(function (_, el) {
if (typeof fn === "function") el.addEventListener("click", function (ev) { fn.call(el, ev); });
else el.click();
});
};
JQ.prototype.hide = function () {
return this.each(function (_, el) { el.style.display = "none"; });
};
JQ.prototype.show = function () {
return this.each(function (_, el) { el.style.display = ""; });
};
JQ.prototype.parent = function () {
const out = [];
this.elements.forEach(function (el) {
if (el.parentElement && out.indexOf(el.parentElement) === -1) out.push(el.parentElement);
});
return new JQ(out);
};
JQ.prototype.children = function () {
const out = [];
this.elements.forEach(function (el) {
Array.from(el.children).forEach(function (c) { out.push(c); });
});
return new JQ(out);
};
JQ.prototype.find = function (sel) {
const out = [];
this.elements.forEach(function (el) {
Array.from(el.querySelectorAll(sel)).forEach(function (c) {
if (out.indexOf(c) === -1) out.push(c);
});
});
return new JQ(out);
};
function $(selector) {
if (selector instanceof Element) return new JQ([selector]);
if (typeof selector === "string") return new JQ(Array.from(document.querySelectorAll(selector)));
return new JQ([]);
}
$.trim = function (str) { return String(str).trim(); };
$.each = function (arr, fn) { arr.forEach(function (item, idx) { fn.call(item, idx, item); }); };
$.fn = JQ.prototype;
$.fn.jquery = "3.7.1-offline-lab";
global.$ = global.jQuery = $;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery 简介离线实验</title>
<script>{MINI_JQ}</script>
</head>
<body>
<section id="workspace">
<h2 id="title">原始标题</h2>
<ul id="features">
<li class="feat">HTML 元素选取</li>
<li class="feat">CSS 操作</li>
</ul>
<button id="btn-action" type="button">触发事件</button>
<div id="panel">特效面板</div>
</section>
<script>
window.__clicks = 0;
$("#btn-action").click(function () {{
window.__clicks += 1;
$("#title").text("已响应点击").css("color", "rgb(37, 99, 235)");
$("#features").append('<li class="feat">事件处理</li>');
}});
$.fn.highlight = function (bg) {{
return this.css("backgroundColor", bg);
}};
</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 pw:
browser = launch_browser(pw)
try:
page = browser.new_page()
page.set_content(HTML_DOC, wait_until="load")
# Case 1: HTML selection, DOM mutation, CSS & event handling
page.locator("#btn-action").click()
act1 = page.evaluate(
"""() => ({
clicks: window.__clicks,
title_text: $("#title").text(),
title_color: $("#title").css("color"),
feat_count: $(".feat").length
})"""
)
exp1 = {
"clicks": 1,
"title_text": "已响应点击",
"title_color": "rgb(37, 99, 235)",
"feat_count": 3,
}
cases.append(dict(name="core_dom_css_events", passed=(act1 == exp1), expected=exp1, actual=act1))
# Case 2: Effects, DOM traversal and utilities
act2 = page.evaluate(
"""() => {
$("#panel").hide();
const hiddenDisp = getComputedStyle(document.getElementById("panel")).display;
$("#panel").show();
const shownDisp = getComputedStyle(document.getElementById("panel")).display;
const parentId = $("#features").parent().elements[0].id;
const childCount = $("#features").children().length;
const foundCount = $("#workspace").find("li").length;
const trimmed = $.trim(" jQuery Utilities ");
const collected = [];
$.each(["HTML", "CSS", "JavaScript"], (i, v) => collected.push(i + ":" + v));
return { hiddenDisp, shownDisp, parentId, childCount, foundCount, trimmed, collected };
}"""
)
exp2 = {
"hiddenDisp": "none",
"shownDisp": "block",
"parentId": "workspace",
"childCount": 3,
"foundCount": 3,
"trimmed": "jQuery Utilities",
"collected": ["0:HTML", "1:CSS", "2:JavaScript"],
}
cases.append(dict(name="effects_traversal_utilities", passed=(act2 == exp2), expected=exp2, actual=act2))
# Case 3: Plugin extensibility via $.fn and browser DOM compatibility surface
act3 = page.evaluate(
"""() => {
$("#panel").highlight("rgb(254, 243, 199)");
return {
panel_bg: getComputedStyle(document.getElementById("panel")).backgroundColor,
has_plugin: typeof $.fn.highlight === "function",
version_tag: $.fn.jquery,
has_querySelectorAll: typeof document.querySelectorAll === "function"
};
}"""
)
exp3 = {
"panel_bg": "rgb(254, 243, 199)",
"has_plugin": True,
"version_tag": "3.7.1-offline-lab",
"has_querySelectorAll": True,
}
cases.append(dict(name="plugin_extension_and_compat", passed=(act3 == exp3), expected=exp3, actual=act3))
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-intro-lab/explore-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a895.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip