"""Offline Playwright Chromium lab for Foundation 5 Ch 12 (images)."""
import json
from playwright.sync_api import sync_playwright
FOUNDATION_IMAGES_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 20px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #222; background: #fff; }
img {
max-width: 100%;
height: auto;
display: inline-block;
vertical-align: middle;
}
.th {
line-height: 0;
display: inline-block;
max-width: 100%;
border: solid 4px #FFFFFF;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2);
transition: all 200ms ease-out;
}
.th:hover, .th:focus {
box-shadow: 0 0 6px 1px rgba(0, 140, 186, 0.5);
}
.th.radius {
border-radius: 3px;
}
ul.clearing-thumbs {
list-style: none;
margin: 0 0 1rem 0;
padding: 0;
display: flex;
gap: 10px;
}
ul.clearing-thumbs.clearing-feature li {
display: none;
}
ul.clearing-thumbs.clearing-feature li.clearing-featured-img {
display: list-item;
}
.clearing-blackout {
display: none;
position: fixed;
inset: 0;
background: #333333;
color: #ffffff;
z-index: 998;
padding: 24px;
text-align: center;
}
.clearing-blackout.open {
display: block;
}
.clearing-caption {
margin-top: 12px;
font-size: 0.9rem;
color: #cccccc;
}
"""
def make_svg(w, h, color, label):
return (
"data:image/svg+xml;utf8,"
f"<svg xmlns='http://www.w3.org/2000/svg' width='{w}' height='{h}'>"
f"<rect width='{w}' height='{h}' fill='{color}'/>"
f"<text x='{w // 2}' y='{h // 2}' text-anchor='middle' fill='white' font-size='18'>{label}</text>"
"</svg>"
)
IMG_PARIS = make_svg(400, 200, "%232b6cb0", "Paris")
IMG_ROCK_SM = make_svg(200, 100, "%2338a169", "Rock-Thumb")
IMG_ROCK_LG = make_svg(600, 400, "%232f855a", "Rock-Full")
IMG_SKIES_SM = make_svg(200, 100, "%233182ce", "Skies-Thumb")
IMG_SKIES_LG = make_svg(600, 400, "%232b6cb0", "Skies-Full")
IMG_LIGHTS_SM = make_svg(200, 100, "%23805ad5", "Lights-Thumb")
IMG_LIGHTS_LG = make_svg(600, 400, "%236b46c1", "Lights-Full")
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_IMAGES_CSS}</style></head>
<body>
<div id="resp-box" style="width: 600px;">
<a id="thumb-basic" href="{IMG_PARIS}" class="th">
<img id="img-basic" src="{IMG_PARIS}" alt="Paris">
</a>
</div>
<div style="margin-top: 16px;">
<a id="thumb-radius" href="{IMG_PARIS}" class="th radius">
<img src="{IMG_PARIS}" alt="Paris Radius" width="200" height="100">
</a>
</div>
<ul id="gallery-main" class="clearing-thumbs" data-clearing>
<li><a href="{IMG_ROCK_LG}" class="th"><img data-caption="<h2>Pulpit Rock</h2><p>Located in Norway</p>" src="{IMG_ROCK_SM}" alt="Rock"></a></li>
<li><a href="{IMG_SKIES_LG}" class="th"><img data-caption="Sunrise Skies" src="{IMG_SKIES_SM}" alt="Skies"></a></li>
<li><a href="{IMG_LIGHTS_LG}" class="th"><img data-caption="Northern Lights" src="{IMG_LIGHTS_SM}" alt="Lights"></a></li>
</ul>
<ul id="gallery-feature" class="clearing-thumbs clearing-feature" data-clearing>
<li id="feat-1"><a href="{IMG_ROCK_LG}" class="th"><img data-caption="The Pulpit Rock" src="{IMG_ROCK_SM}" alt="Rock"></a></li>
<li id="feat-2"><a href="{IMG_SKIES_LG}" class="th"><img data-caption="Sunrise Skies" src="{IMG_SKIES_SM}" alt="Skies"></a></li>
<li id="feat-3" class="clearing-featured-img"><a href="{IMG_LIGHTS_LG}" class="th"><img data-caption="Northern Lights" src="{IMG_LIGHTS_SM}" alt="Lights"></a></li>
</ul>
<div id="clearing-modal" class="clearing-blackout" aria-hidden="true">
<button id="clearing-close" type="button">×</button>
<button id="clearing-prev" type="button">Prev</button>
<button id="clearing-next" type="button">Next</button>
<div><img id="clearing-visible-img" src="" alt="Preview"></div>
<div id="clearing-caption" class="clearing-caption"></div>
<div id="clearing-counter"></div>
</div>
<script>
(function () {{
const modal = document.getElementById('clearing-modal');
const vImg = document.getElementById('clearing-visible-img');
const vCap = document.getElementById('clearing-caption');
const vCnt = document.getElementById('clearing-counter');
let currentList = [];
let currentIdx = 0;
function renderModal() {{
const item = currentList[currentIdx];
vImg.src = item.href;
vCap.innerHTML = item.caption || '';
vCnt.textContent = (currentIdx + 1) + '/' + currentList.length;
}}
document.querySelectorAll('ul.clearing-thumbs[data-clearing]').forEach((ul) => {{
const anchors = Array.from(ul.querySelectorAll('li > a'));
const items = anchors.map((a) => {{
const im = a.querySelector('img');
return {{ href: a.getAttribute('href'), caption: im ? (im.getAttribute('data-caption') || '') : '' }};
}});
anchors.forEach((a, idx) => {{
a.addEventListener('click', (e) => {{
e.preventDefault();
currentList = items;
currentIdx = idx;
modal.classList.add('open');
modal.setAttribute('aria-hidden', 'false');
renderModal();
}});
}});
}});
document.getElementById('clearing-next').addEventListener('click', () => {{
if (!currentList.length) return;
currentIdx = (currentIdx + 1) % currentList.length;
renderModal();
}});
document.getElementById('clearing-prev').addEventListener('click', () => {{
if (!currentList.length) return;
currentIdx = (currentIdx - 1 + currentList.length) % currentList.length;
renderModal();
}});
document.getElementById('clearing-close').addEventListener('click', () => {{
modal.classList.remove('open');
modal.setAttribute('aria-hidden', 'true');
}});
}})();
</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)
page = browser.new_page(viewport={"width": 1000, "height": 900})
page.set_content(HTML_PAGE)
# Case 1: responsive_img_and_th_thumbnail
wide = page.evaluate("""() => {
const a = document.getElementById('thumb-basic');
const img = document.getElementById('img-basic');
const as = getComputedStyle(a);
const is = getComputedStyle(img);
return {
th_display: as.display,
th_border: as.borderTopWidth + ' ' + as.borderTopStyle + ' ' + as.borderTopColor,
th_shadow_idle: as.boxShadow,
img_max_width: is.maxWidth,
wide_w: Math.round(img.getBoundingClientRect().width),
wide_h: Math.round(img.getBoundingClientRect().height),
};
}""")
page.locator("#thumb-basic").hover()
page.wait_for_function(
"() => getComputedStyle(document.getElementById('thumb-basic')).boxShadow.includes('0, 140, 186')"
)
hover_shadow = page.evaluate("""() => getComputedStyle(document.getElementById('thumb-basic')).boxShadow""")
narrow = page.evaluate("""() => {
document.getElementById('resp-box').style.width = '208px';
const img = document.getElementById('img-basic');
return {
narrow_w: Math.round(img.getBoundingClientRect().width),
narrow_h: Math.round(img.getBoundingClientRect().height),
};
}""")
act_1 = {
"th_display": wide["th_display"],
"th_border": wide["th_border"],
"hover_shadow_changed": hover_shadow != wide["th_shadow_idle"],
"hover_has_blue_glow": "0, 140, 186" in hover_shadow,
"img_max_width": wide["img_max_width"],
"wide_dims": [wide["wide_w"], wide["wide_h"]],
"narrow_dims": [narrow["narrow_w"], narrow["narrow_h"]],
}
exp_1 = {
"th_display": "inline-block",
"th_border": "4px solid rgb(255, 255, 255)",
"hover_shadow_changed": True,
"hover_has_blue_glow": True,
"img_max_width": "100%",
"wide_dims": [400, 200],
"narrow_dims": [200, 100],
}
cases.append({
"name": "responsive_img_and_th_thumbnail",
"expected": exp_1,
"actual": act_1,
"passed": act_1 == exp_1,
})
# Case 2: radius_thumbnail_corners
act_2 = page.evaluate("""() => {
const s1 = getComputedStyle(document.getElementById('thumb-basic'));
const s2 = getComputedStyle(document.getElementById('thumb-radius'));
return {
basic_radius: s1.borderRadius,
radius_th_radius: s2.borderRadius,
radius_th_border: s2.borderTopWidth,
};
}""")
exp_2 = {
"basic_radius": "0px",
"radius_th_radius": "3px",
"radius_th_border": "4px",
}
cases.append({
"name": "radius_thumbnail_corners",
"expected": exp_2,
"actual": act_2,
"passed": act_2 == exp_2,
})
# Case 3: clearing_lightbox_and_html_caption
page.locator("#gallery-main li").nth(0).locator("a").click()
s_open = page.evaluate("""() => ({
open: document.getElementById('clearing-modal').classList.contains('open'),
caption_h2: document.querySelector('#clearing-caption h2')?.textContent || '',
caption_p: document.querySelector('#clearing-caption p')?.textContent || '',
counter: document.getElementById('clearing-counter').textContent,
uses_full_href: document.getElementById('clearing-visible-img').src.includes('Rock-Full'),
})""")
page.locator("#clearing-next").click()
s_next = page.evaluate("""() => ({
caption_text: document.getElementById('clearing-caption').textContent,
counter: document.getElementById('clearing-counter').textContent,
uses_full_href: document.getElementById('clearing-visible-img').src.includes('Skies-Full'),
})""")
page.locator("#clearing-close").click()
s_closed = page.evaluate("""() => document.getElementById('clearing-modal').classList.contains('open')""")
act_3 = {
"opened": s_open["open"],
"html_caption_h2": s_open["caption_h2"],
"html_caption_p": s_open["caption_p"],
"first_counter": s_open["counter"],
"first_full_img": s_open["uses_full_href"],
"next_caption": s_next["caption_text"],
"next_counter": s_next["counter"],
"next_full_img": s_next["uses_full_href"],
"closed_after_click": not s_closed,
}
exp_3 = {
"opened": True,
"html_caption_h2": "Pulpit Rock",
"html_caption_p": "Located in Norway",
"first_counter": "1/3",
"first_full_img": True,
"next_caption": "Sunrise Skies",
"next_counter": "2/3",
"next_full_img": True,
"closed_after_click": True,
}
cases.append({
"name": "clearing_lightbox_and_html_caption",
"expected": exp_3,
"actual": act_3,
"passed": act_3 == exp_3,
})
# Case 4: clearing_feature_single_thumb
vis_before = page.evaluate("""() => ({
li1: getComputedStyle(document.getElementById('feat-1')).display,
li2: getComputedStyle(document.getElementById('feat-2')).display,
li3: getComputedStyle(document.getElementById('feat-3')).display,
})""")
page.locator("#feat-3 a").click()
feat_open = page.evaluate("""() => ({
open: document.getElementById('clearing-modal').classList.contains('open'),
caption: document.getElementById('clearing-caption').textContent,
counter: document.getElementById('clearing-counter').textContent,
})""")
page.locator("#clearing-next").click()
feat_cycle = page.evaluate("""() => ({
caption: document.getElementById('clearing-caption').textContent,
counter: document.getElementById('clearing-counter').textContent,
})""")
act_4 = {
"hidden_items": [vis_before["li1"], vis_before["li2"]],
"featured_display": vis_before["li3"],
"opened_counter": feat_open["counter"],
"opened_caption": feat_open["caption"],
"cycled_counter": feat_cycle["counter"],
"cycled_caption": feat_cycle["caption"],
}
exp_4 = {
"hidden_items": ["none", "none"],
"featured_display": "list-item",
"opened_counter": "3/3",
"opened_caption": "Northern Lights",
"cycled_counter": "1/3",
"cycled_caption": "The Pulpit Rock",
}
cases.append({
"name": "clearing_feature_single_thumb",
"expected": exp_4,
"actual": act_4,
"passed": act_4 == exp_4,
})
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/foundation-images-lab/explore-images.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-images.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a739.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a755.zip