"""Offline Playwright Chromium lab for Chapter 14: Playwright Mobile Testing."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright
class MobileHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_GET(self):
html = (
"<!doctype html><html><head>"
"<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
"<title>Mobile Lab</title></head><body>"
"<button id='submit' style='width:120px;height:44px'>提交</button>"
"<div id='pad' style='width:240px;height:160px;background:#eef;margin-top:10px'></div>"
"<div id='log'></div>"
"<script>"
"window.__events=[];"
"const btn=document.getElementById('submit');"
"btn.addEventListener('touchstart',()=>window.__events.push('btn:touchstart'));"
"btn.addEventListener('click',()=>window.__events.push('btn:click'));"
"const pad=document.getElementById('pad');"
"pad.addEventListener('touchstart',e=>{"
" const t=e.touches[0];"
" window.__events.push(`pad:${Math.round(t.clientX)},${Math.round(t.clientY)}`);"
"});"
"</script></body></html>"
).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(html)))
self.end_headers()
self.wfile.write(html)
def launch_browser(p):
for kwargs in (dict(channel="chrome", headless=True), dict(channel="msedge", headless=True), dict(headless=True)):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No local Chromium executable found")
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), MobileHandler)
port = server.server_address[1]
base_url = f"http://127.0.0.1:{port}"
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
# Case 1: Device emulation (iPhone 12 & Pixel 5)
ip12 = p.devices["iPhone 12"]
px5 = p.devices["Pixel 5"]
ctx_ip = browser.new_context(**ip12)
pg_ip = ctx_ip.new_page()
pg_ip.goto(f"{base_url}/")
ip_info = pg_ip.evaluate(
"() => ({w: window.innerWidth, h: window.innerHeight, dpr: window.devicePixelRatio,"
" hasIPhoneUA: navigator.userAgent.includes('iPhone'), touch: navigator.maxTouchPoints > 0})"
)
ctx_ip.close()
ctx_px = browser.new_context(**px5)
pg_px = ctx_px.new_page()
pg_px.goto(f"{base_url}/")
px_info = pg_px.evaluate(
"() => ({w: window.innerWidth, h: window.innerHeight, dpr: window.devicePixelRatio,"
" hasPixelUA: navigator.userAgent.includes('Pixel 5'), touch: navigator.maxTouchPoints > 0})"
)
ctx_px.close()
actual1 = {"iphone12": ip_info, "pixel5": px_info}
expected1 = {
"iphone12": {
"w": ip12["viewport"]["width"],
"h": ip12["viewport"]["height"],
"dpr": ip12["device_scale_factor"],
"hasIPhoneUA": True,
"touch": True,
},
"pixel5": {
"w": px5["viewport"]["width"],
"h": px5["viewport"]["height"],
"dpr": px5["device_scale_factor"],
"hasPixelUA": True,
"touch": True,
},
}
cases.append(dict(name="device_emulation_iphone12_and_pixel5", expected=expected1, actual=actual1, passed=actual1 == expected1))
# Case 2: Touch tap on element + touchscreen.tap(x, y) + API capability check
ctx_t = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True)
pg_t = ctx_t.new_page()
pg_t.goto(f"{base_url}/")
pg_t.tap("button#submit")
box = pg_t.locator("#pad").bounding_box()
tap_x = round(box["x"] + 40)
tap_y = round(box["y"] + 30)
pg_t.touchscreen.tap(tap_x, tap_y)
events = pg_t.evaluate("() => window.__events")
ts_methods = [m for m in ("tap", "swipe", "down", "up") if hasattr(pg_t.touchscreen, m)]
ctx_t.close()
actual2 = {
"btn_tapped": "btn:touchstart" in events and "btn:click" in events,
"pad_event": events[-1],
"touchscreen_builtin_methods": ts_methods,
}
expected2 = {
"btn_tapped": True,
"pad_event": f"pad:{tap_x},{tap_y}",
"touchscreen_builtin_methods": ["tap"],
}
cases.append(dict(name="touch_tap_and_touchscreen_coords", expected=expected2, actual=actual2, passed=actual2 == expected2))
# Case 3: Geolocation + permissions + dynamic set_geolocation
ctx_geo = browser.new_context(
**px5,
geolocation={"longitude": 116.4074, "latitude": 39.9042},
permissions=["geolocation", "notifications"],
)
pg_geo = ctx_geo.new_page()
pg_geo.goto(f"{base_url}/")
geo1 = pg_geo.evaluate(
"() => new Promise((res, rej) => navigator.geolocation.getCurrentPosition("
" p => res([Number(p.coords.latitude.toFixed(4)), Number(p.coords.longitude.toFixed(4))]),"
" e => rej(e.message)))"
)
perm_geo = pg_geo.evaluate("async () => (await navigator.permissions.query({name: 'geolocation'})).state")
perm_notif = pg_geo.evaluate("() => Notification.permission")
ctx_geo.set_geolocation({"longitude": 121.4737, "latitude": 31.2304})
geo2 = pg_geo.evaluate(
"() => new Promise((res, rej) => navigator.geolocation.getCurrentPosition("
" p => res([Number(p.coords.latitude.toFixed(4)), Number(p.coords.longitude.toFixed(4))]),"
" e => rej(e.message)))"
)
ctx_geo.close()
actual3 = {
"beijing": geo1,
"shanghai": geo2,
"geolocation_perm": perm_geo,
"notification_perm": perm_notif,
}
expected3 = {
"beijing": [39.9042, 116.4074],
"shanghai": [31.2304, 121.4737],
"geolocation_perm": "granted",
"notification_perm": "granted",
}
cases.append(dict(name="geolocation_and_permissions_api", expected=expected3, actual=actual3, passed=actual3 == expected3))
# Case 4: Portrait vs landscape viewport switch + built-in device catalog check
ctx_ori = browser.new_context(viewport={"width": 375, "height": 812}, is_mobile=True, has_touch=True)
pg_ori = ctx_ori.new_page()
pg_ori.goto(f"{base_url}/")
portrait = pg_ori.evaluate("() => window.matchMedia('(orientation: portrait)').matches")
pg_ori.set_viewport_size({"width": 812, "height": 375})
landscape = pg_ori.evaluate("() => window.matchMedia('(orientation: landscape)').matches")
ctx_ori.close()
sample_devices = ["iPhone SE", "iPhone 12", "Pixel 5", "iPad (gen 6)", "Galaxy S8"]
present_flags = [name in p.devices for name in sample_devices]
actual4 = {
"portrait_match": portrait,
"landscape_match": landscape,
"sample_devices_present": present_flags,
}
expected4 = {
"portrait_match": True,
"landscape_match": True,
"sample_devices_present": [True, True, True, True, True],
}
cases.append(dict(name="orientation_switch_and_device_catalog", expected=expected4, actual=actual4, passed=actual4 == expected4))
browser.close()
finally:
server.shutdown()
server.server_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/playwright-mobile-test-lab/explore-mobile-test.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-mobile-test.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a621.zip