"""Offline Playwright Chromium lab for AngularJS Ch 20: bootstrap."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS Bootstrap Lab</title>
<style>
/* Offline Bootstrap 3.3.4 subset CSS equivalence for tested classes */
* { box-sizing: border-box; }
.container { width: 750px; margin-right: auto; margin-left: auto; padding-left: 15px; padding-right: 15px; }
.table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
.table th, .table td { padding: 8px; border-top: 1px solid #ddd; text-align: left; }
.table-striped > tbody > tr:nth-of-type(odd) { background-color: #f9f9f9; }
.btn { display: inline-block; padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px; background: #fff; cursor: pointer; }
.btn-success { color: #fff; background-color: #5cb85c; border-color: #4cae4c; }
.btn:disabled { opacity: 0.65; cursor: not-allowed; }
.glyphicon { display: inline-block; margin-right: 4px; }
.form-horizontal .form-group { display: flex; align-items: center; margin-bottom: 12px; }
.col-sm-2 { width: 16.666667%; padding-right: 10px; }
.col-sm-10 { width: 83.333333%; }
.control-label { text-align: right; font-weight: bold; }
.ng-hide { display: none !important; }
</style>
</head>
<body>
<div id="root-container" class="container">
<h3>Users</h3>
<table id="users-table" class="table table-striped">
<thead>
<tr><th>Edit</th><th>First Name</th><th>Last Name</th></tr>
</thead>
<tbody id="users-tbody"></tbody>
</table>
<hr>
<button id="btn-create" class="btn btn-success">
<span class="glyphicon glyphicon-user"></span> Create New User
</button>
<hr>
<h3 id="hdr-create">Create New User:</h3>
<h3 id="hdr-edit" class="ng-hide">Edit User:</h3>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">First Name:</label>
<div class="col-sm-10">
<input id="in-fname" type="text" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Last Name:</label>
<div class="col-sm-10">
<input id="in-lname" type="text" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Password:</label>
<div class="col-sm-10">
<input id="in-pass1" type="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Repeat:</label>
<div class="col-sm-10">
<input id="in-pass2" type="password" placeholder="Repeat Password">
</div>
</div>
</form>
<hr>
<button id="btn-save" class="btn btn-success">
<span class="glyphicon glyphicon-save"></span> Save Changes
</button>
</div>
<script>
(function () {
const scope = {
fName: "",
lName: "",
passw1: "",
passw2: "",
users: [
{ id: 1, fName: "Hege", lName: "Pege" },
{ id: 2, fName: "Kim", lName: "Pim" },
{ id: 3, fName: "Sal", lName: "Smith" },
{ id: 4, fName: "Jack", lName: "Jones" },
{ id: 5, fName: "John", lName: "Doe" },
{ id: 6, fName: "Peter", lName: "Pan" }
],
edit: true,
error: false,
incomplete: false
};
const tbody = document.getElementById("users-tbody");
const hdrCreate = document.getElementById("hdr-create");
const hdrEdit = document.getElementById("hdr-edit");
const inF = document.getElementById("in-fname");
const inL = document.getElementById("in-lname");
const inP1 = document.getElementById("in-pass1");
const inP2 = document.getElementById("in-pass2");
const btnSave = document.getElementById("btn-save");
function test() {
scope.error = scope.passw1 !== scope.passw2;
scope.incomplete = false;
if (scope.edit && (!scope.fName.length || !scope.lName.length || !scope.passw1.length || !scope.passw2.length)) {
scope.incomplete = true;
}
render();
}
function editUser(id) {
if (id === "new") {
scope.edit = true;
scope.incomplete = true;
scope.fName = "";
scope.lName = "";
scope.passw1 = "";
scope.passw2 = "";
} else {
scope.edit = false;
scope.fName = scope.users[id - 1].fName;
scope.lName = scope.users[id - 1].lName;
}
test();
}
function render() {
hdrCreate.classList.toggle("ng-hide", !scope.edit);
hdrEdit.classList.toggle("ng-hide", scope.edit);
inF.value = scope.fName;
inL.value = scope.lName;
inP1.value = scope.passw1;
inP2.value = scope.passw2;
inF.disabled = !scope.edit;
inL.disabled = !scope.edit;
btnSave.disabled = scope.error || scope.incomplete;
}
scope.users.forEach((u) => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td><button class="btn" data-edit-id="${u.id}"><span class="glyphicon glyphicon-pencil"></span> Edit</button></td>
<td>${u.fName}</td>
<td>${u.lName}</td>
`;
tr.querySelector("button").addEventListener("click", () => editUser(u.id));
tbody.appendChild(tr);
});
document.getElementById("btn-create").addEventListener("click", () => editUser("new"));
inF.addEventListener("input", () => { scope.fName = inF.value; test(); });
inL.addEventListener("input", () => { scope.lName = inL.value; test(); });
inP1.addEventListener("input", () => { scope.passw1 = inP1.value; test(); });
inP2.addEventListener("input", () => { scope.passw2 = inP2.value; test(); });
// Initial $watch execution on startup
test();
window.__userScope = scope;
})();
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.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": 1024, "height": 768})
page.set_content(HTML_DOC)
# Case 1: Bootstrap CSS classes rendered on table-striped, btn-success, container, col-sm-2/10
actual1 = page.evaluate("""() => {
const rows = document.querySelectorAll("#users-tbody tr");
const createBtn = document.getElementById("btn-create");
const lbl = document.querySelector(".col-sm-2.control-label");
const fieldWrap = document.querySelector(".col-sm-10");
return {
rowCount: rows.length,
row0Bg: getComputedStyle(rows[0]).backgroundColor,
row1Bg: getComputedStyle(rows[1]).backgroundColor,
btnSuccessBg: getComputedStyle(createBtn).backgroundColor,
btnSuccessColor: getComputedStyle(createBtn).color,
colRatioApprox: Math.round(fieldWrap.getBoundingClientRect().width / lbl.getBoundingClientRect().width)
};
}""")
expected1 = {
"rowCount": 6,
"row0Bg": "rgb(249, 249, 249)",
"row1Bg": "rgba(0, 0, 0, 0)",
"btnSuccessBg": "rgb(92, 184, 92)",
"btnSuccessColor": "rgb(255, 255, 255)",
"colRatioApprox": 5,
}
cases.append({"name": "bootstrap_striped_table_button_and_grid_css", "expected": expected1, "actual": actual1, "passed": actual1 == expected1})
# Case 2: editUser(5) switches to Edit User mode, locks fName/lName, populates John Doe
page.click("button[data-edit-id='5']")
actual2 = page.evaluate("""() => ({
edit: window.__userScope.edit,
fName: document.getElementById("in-fname").value,
lName: document.getElementById("in-lname").value,
fNameDisabled: document.getElementById("in-fname").disabled,
lNameDisabled: document.getElementById("in-lname").disabled,
createHdrDisplay: getComputedStyle(document.getElementById("hdr-create")).display,
editHdrDisplay: getComputedStyle(document.getElementById("hdr-edit")).display,
saveDisabled: document.getElementById("btn-save").disabled
})""")
expected2 = {
"edit": False,
"fName": "John",
"lName": "Doe",
"fNameDisabled": True,
"lNameDisabled": True,
"createHdrDisplay": "none",
"editHdrDisplay": "block",
"saveDisabled": False,
}
cases.append({"name": "edit_existing_user_mode_and_field_lock", "expected": expected2, "actual": actual2, "passed": actual2 == expected2})
# Case 3: Create New User mode + $watch password mismatch & completeness gating on Save Changes
page.click("#btn-create")
after_new_disabled = page.evaluate("document.getElementById('btn-save').disabled")
page.fill("#in-fname", "Ada")
page.fill("#in-lname", "Lovelace")
page.fill("#in-pass1", "secret123")
page.fill("#in-pass2", "secret999")
mismatch = page.evaluate("""() => ({
error: window.__userScope.error,
incomplete: window.__userScope.incomplete,
saveDisabled: document.getElementById("btn-save").disabled
})""")
page.fill("#in-pass2", "secret123")
matched = page.evaluate("""() => ({
error: window.__userScope.error,
incomplete: window.__userScope.incomplete,
saveDisabled: document.getElementById("btn-save").disabled
})""")
actual3 = {"after_create_disabled": after_new_disabled, "mismatch": mismatch, "matched": matched}
expected3 = {
"after_create_disabled": True,
"mismatch": {"error": True, "incomplete": False, "saveDisabled": True},
"matched": {"error": False, "incomplete": False, "saveDisabled": False},
}
cases.append({"name": "create_user_watch_password_and_save_gate", "expected": expected3, "actual": actual3, "passed": actual3 == expected3})
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/angularjs-bootstrap-lab/explore-bootstrap.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-bootstrap.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a852.zip