"""Offline Playwright Chromium lab for Bootstrap 4 Ch 01 (tutorial)."""
import json
from playwright.sync_api import sync_playwright
BS4_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 1rem; line-height: 1.5; color: #212529; background: #fff; }
h1, h3, p { margin-top: 0; }
h1 { font-size: 2.5rem; margin-bottom: 0.5rem; }
h3 { font-size: 1.75rem; margin-bottom: 0.5rem; }
p { margin-bottom: 1rem; }
.text-center { text-align: center !important; }
.jumbotron { padding: 2rem 1rem; margin-bottom: 2rem; background-color: #e9ecef; border-radius: 0.3rem; }
@media (min-width: 576px) { .jumbotron { padding: 4rem 2rem; } }
.container { width: 100%; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; }
@media (min-width: 576px) { .container { max-width: 540px; } }
@media (min-width: 768px) { .container { max-width: 720px; } }
@media (min-width: 992px) { .container { max-width: 960px; } }
@media (min-width: 1200px) { .container { max-width: 1140px; } }
.row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }
.col-sm-4 { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; }
@media (min-width: 576px) {
.col-sm-4 { flex: 0 0 33.333333%; max-width: 33.333333%; }
}
"""
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_CSS}</style></head>
<body>
<div id="hero" class="jumbotron text-center">
<h1>我的第一个 Bootstrap 页面</h1>
<p>调整浏览器视口宽度观察响应式排版变化。</p>
</div>
<div id="main-container" class="container">
<div id="main-row" class="row">
<div class="col-sm-4" id="c1">
<h3>第一列</h3>
<p>响应式移动优先栅格示例。</p>
<p>短文本演示。</p>
</div>
<div class="col-sm-4" id="c2">
<h3>第二列</h3>
<p>Bootstrap 4 基于 Flexbox 弹性布局构建栅格列。</p>
<p>当此列内容较多时,同行其它列在宽屏下自动保持等高对齐,无需手动固定高度。</p>
<p>额外补充一行以制造高度差异。</p>
</div>
<div class="col-sm-4" id="c3">
<h3>第三列</h3>
<p>在 576px 以上自动分为三等宽列。</p>
</div>
</div>
</div>
</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)
page = browser.new_page(viewport={"width": 375, "height": 800})
page.set_content(HTML_PAGE)
# Case 1: jumbotron_header_layout
mobile_hero = page.evaluate("""() => {
const s = getComputedStyle(document.getElementById('hero'));
return {
bg: s.backgroundColor,
align: s.textAlign,
padding: s.paddingTop + ' ' + s.paddingRight,
radius: s.borderRadius,
};
}""")
page.set_viewport_size({"width": 992, "height": 800})
desktop_hero = page.evaluate("""() => {
const s = getComputedStyle(document.getElementById('hero'));
return { padding: s.paddingTop + ' ' + s.paddingRight };
}""")
actual_1 = {
"background": mobile_hero["bg"],
"text_align": mobile_hero["align"],
"border_radius": mobile_hero["radius"],
"padding_375": mobile_hero["padding"],
"padding_992": desktop_hero["padding"],
}
expected_1 = {
"background": "rgb(233, 236, 239)",
"text_align": "center",
"border_radius": "4.8px",
"padding_375": "32px 16px",
"padding_992": "64px 32px",
}
cases.append(dict(
name="jumbotron_header_layout",
passed=(actual_1 == expected_1),
expected=expected_1,
actual=actual_1,
))
# Case 2: three_column_responsive_stack
page.set_viewport_size({"width": 375, "height": 800})
mob_cols = page.evaluate("""() => ['#c1', '#c2', '#c3'].map(sel => {
const r = document.querySelector(sel).getBoundingClientRect();
return { w: Math.round(r.width), y: Math.round(r.top) };
})""")
page.set_viewport_size({"width": 992, "height": 800})
desk_cols = page.evaluate("""() => ['#c1', '#c2', '#c3'].map(sel => {
const r = document.querySelector(sel).getBoundingClientRect();
return { w: Math.round(r.width), y: Math.round(r.top) };
})""")
actual_2 = {
"mobile_375_widths": [c["w"] for c in mob_cols],
"mobile_375_stacked": mob_cols[0]["y"] < mob_cols[1]["y"] < mob_cols[2]["y"],
"desktop_992_widths": [c["w"] for c in desk_cols],
"desktop_992_same_row": len({c["y"] for c in desk_cols}) == 1,
}
expected_2 = {
"mobile_375_widths": [375, 375, 375],
"mobile_375_stacked": True,
"desktop_992_widths": [320, 320, 320],
"desktop_992_same_row": True,
}
cases.append(dict(
name="three_column_responsive_stack",
passed=(actual_2 == expected_2),
expected=expected_2,
actual=actual_2,
))
# Case 3: flexbox_equal_height_columns
flex_info = page.evaluate("""() => {
const rowStyle = getComputedStyle(document.getElementById('main-row'));
const heights = ['#c1', '#c2', '#c3'].map(sel => Math.round(document.querySelector(sel).getBoundingClientRect().height));
return {
display: rowStyle.display,
flex_wrap: rowStyle.flexWrap,
equal_heights: new Set(heights).size === 1 && heights[0] > 0,
};
}""")
expected_3 = {"display": "flex", "flex_wrap": "wrap", "equal_heights": True}
cases.append(dict(
name="flexbox_equal_height_columns",
passed=(flex_info == expected_3),
expected=expected_3,
actual=flex_info,
))
# Case 4: container_breakpoint_widths
bp_widths = {}
for vw in (375, 576, 768, 992, 1200):
page.set_viewport_size({"width": vw, "height": 800})
w = page.evaluate("() => Math.round(document.getElementById('main-container').getBoundingClientRect().width)")
bp_widths[str(vw)] = w
expected_4 = {"375": 375, "576": 540, "768": 720, "992": 960, "1200": 1140}
cases.append(dict(
name="container_breakpoint_widths",
passed=(bp_widths == expected_4),
expected=expected_4,
actual=bp_widths,
))
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/bootstrap4-tutorial-lab/explore-tutorial.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联35章) · 含当前章节或实例 · mbskycom202612a664.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a696.zip