Playwright 设备与浏览器模拟
核对 Playwright 移动设备预设与自定义视口、地理位置、语言时区、深浅色方案、离线状态、权限授予及 Cookie/Storage 操作与离线 Chromium 实测。
学完这一章,你能够
- 核对 Playwright 移动设备预设与自定义视口、地理位置、语言时区、深浅色方案、离线状态、权限授予及 Cookie/Storage 操作与离线 Chromium 实测。
移动端设备预设与手动视口模拟
Playwright 支持在创建 `BrowserContext` 时统一模拟移动设备、地理位置、时区、语言、配色方案及网络离线状态。通过内置 `devices` 预设(如 `devices['iPhone 15']`、`devices['Pixel 7']`),可一键注入对应机型的视口尺寸、设备像素比(DPR)、User-Agent 与触控能力,也可在 `playwright.config.ts` 的 `projects` 中按项目复用。本站离线实测 `iPhone 15` 渲染视口为 `393×659`、`devicePixelRatio = 3`,`Pixel 7` 为 `412×839`、`devicePixelRatio = 2.625`,两者均包含对应机型 UA 且 `navigator.maxTouchPoints > 0`。
若无需完整设备档案,可直接向 `browser.newContext()`(Python 为 `browser.new_context()`)手动传入 `viewport`、`deviceScaleFactor`、`isMobile`、`hasTouch` 与 `userAgent`。本站以 `375×812`、`device_scale_factor=3`、移动端触控及自定义 UA 创建上下文并实测,页面读回 `innerWidth = 375`、`innerHeight = 812`、`devicePixelRatio = 3` 且成功命中自定义 UA。
地理位置、时区语言、颜色方案与离线模拟
测试定位相关功能时,先通过 `context.grantPermissions(['geolocation'])` 授权,再调用 `context.setGeolocation({ latitude, longitude })` 注入经纬度坐标。本站在本地回环安全上下文中设置北京坐标 `[39.9042, 116.4074]`,`navigator.geolocation.getCurrentPosition()` 精确返回 `[39.9042, 116.4074]`。
国际化与跨时区验证通过上下文选项 `locale` 与官方时区选项 `timezoneId`(Python 为 `timezone_id`,部分入门示例误写作 `timezone`,实际以官方 `timezoneId` 为准)完成,也可在 `playwright.config.ts` 的 `use` 中全局配置。本站实测中文上海上下文返回 `navigator.language = 'zh-CN'`、`Intl` 时区 `'Asia/Shanghai'`,美式纽约上下文返回 `'en-US'` 与 `'America/New_York'`。
通过 `colorScheme`(可选 `'light'`、`'dark'`、`'no-preference'`)可测试 CSS `prefers-color-scheme` 媒体查询,亦可在配置文件中拆分浅色与深色 `projects`。本站实测 `color_scheme='dark'` 命中深色媒体查询并将页面背景渲染为 `rgb(18, 18, 18)`,`color_scheme='light'` 不命中深色查询;此外通过 `context.set_offline(True)` 实测 `navigator.onLine` 变为 `false` 且 `fetch('/api/ping')` 抛出网络异常,调用 `set_offline(False)` 后恢复在线。
浏览器权限、Cookie 与 Web Storage 操作
使用 `context.grantPermissions()` 可批量授予 `geolocation`、`notifications`、`camera`、`microphone`、`clipboard-read`、`clipboard-write` 等权限,调用 `context.clearPermissions()` 则重置已授权限。本站实测授予后 `geolocation` 与 `Notification.permission` 均为 `'granted'`,清除后 `geolocation` 权限状态恢复为 `'prompt'`。
Cookie 属于 `BrowserContext` 级别状态:调用 `context.addCookies()` 写入、`context.cookies()`(或按 URL 过滤)读取、`context.clearCookies()` 清空。本站实测写入 `app_session`(`httpOnly: true`、`sameSite: 'Lax'`)与 `theme_pref`(`httpOnly: false`、`sameSite: 'Strict'`)共 2 条 Cookie:服务端请求头同时收到两者,而页面 `document.cookie` 仅可见 `theme_pref=dark`(`httpOnly` 生效),清空后剩余 `0` 条。
`localStorage` 与 `sessionStorage` 可在目标源加载后借助 `page.evaluate()` 读写与清空。Cookie 应在 `page.goto()` 前通过上下文注入;对于页面首次加载就需要读取的 Storage 数据,因空白页 `about:blank` 不存在业务源,工程上应通过 `context.addInitScript()` 或 `storageState` 在导航前预置。本站实测 `add_init_script` 预置的 `preload_key` 在首屏脚本中立即渲染为 `'ready_before_load'`,后续 `localStorage`/`sessionStorage` 读写与清空均返回 `[0, 0]`。
常用 locale 语言地区值
| locale | 语言/地区 |
| 'zh-CN' | 简体中文(中国大陆),实测 navigator.language 返回 zh-CN |
| 'zh-TW' | 繁体中文(中国台湾地区) |
| 'en-US' | 英语(美国),实测 navigator.language 返回 en-US |
| 'ja-JP' | 日语(日本) |
| 'ko-KR' | 韩语(韩国) |
Cookie 对象核心字段说明
| 字段 | 类型 | 说明 |
| name | string | Cookie 名称,如实测中的 app_session |
| value | string | Cookie 存储的字符串值 |
| domain | string | 生效域名(本地回环实验为 127.0.0.1) |
| path | string | 生效路径,默认 '/' |
| expires | number | 过期时间戳(Unix 秒级时间戳),省略则为会话 Cookie |
| httpOnly | boolean | 为 true 时仅随 HTTP 请求发送,document.cookie 不可读取 |
| secure | boolean | 为 true 时仅通过 HTTPS 安全通道传输 |
| sameSite | string | 跨站发送策略:'Strict' | 'Lax' | 'None' |
运行设备预设、地理位置、时区语言、深浅色离线、权限与 Cookie/Storage 实测
展开查看收起
"""Offline Playwright Chromium lab for Chapter 31 (emulation): devices, viewport, geolocation, locale/timezone, color scheme, offline, permissions, cookies, storage."""
import http.server
import json
import os
import threading
from playwright.sync_api import sync_playwright
MAP_HTML = """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模拟环境实验室</title>
<style>
body { background: #ffffff; color: #111111; }
@media (prefers-color-scheme: dark) {
body { background: #121212; color: #f5f5f5; }
}
</style>
</head>
<body>
<h1 id="heading">模拟环境页面</h1>
<div id="preload-storage"></div>
<script>
document.getElementById('preload-storage').textContent =
localStorage.getItem('preload_key') || 'empty';
</script>
</body>
</html>"""
class _Handler(http.server.BaseHTTPRequestHandler):
last_cookie_header = ""
def do_GET(self):
_Handler.last_cookie_header = self.headers.get("Cookie", "")
if self.path == "/api/ping":
payload = json.dumps({"ok": True}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
return
data = MAP_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(data)))
self.end_headers()
try:
self.wfile.write(data)
except (ConnectionAbortedError, ConnectionResetError, BrokenPipeError):
pass
def log_message(self, format, *args):
pass
def launch_browser(p):
exe = p.chromium.executable_path
if exe and os.path.exists(exe):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
return p.chromium.launch(headless=True)
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
port = server.server_address[1]
base_url = f"http://127.0.0.1:{port}"
threading.Thread(target=server.serve_forever, daemon=True).start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
# Case 1: Built-in device presets (iPhone 15, Pixel 7) & manual viewport config
ip15 = p.devices["iPhone 15"]
px7 = p.devices["Pixel 7"]
ctx_ip = browser.new_context(**ip15)
pg_ip = ctx_ip.new_page()
pg_ip.goto(f"{base_url}/")
ip_obs = pg_ip.evaluate(
"() => ({w: window.innerWidth, h: window.innerHeight, dpr: window.devicePixelRatio,"
" uaHasIPhone: navigator.userAgent.includes('iPhone'), touch: navigator.maxTouchPoints > 0})"
)
ctx_ip.close()
ctx_px = browser.new_context(**px7)
pg_px = ctx_px.new_page()
pg_px.goto(f"{base_url}/")
px_obs = pg_px.evaluate(
"() => ({w: window.innerWidth, h: window.innerHeight, dpr: window.devicePixelRatio,"
" uaHasPixel7: navigator.userAgent.includes('Pixel 7'), touch: navigator.maxTouchPoints > 0})"
)
ctx_px.close()
ctx_manual = browser.new_context(
viewport={"width": 375, "height": 812},
device_scale_factor=3,
is_mobile=True,
has_touch=True,
user_agent="Mozilla/5.0 (Custom Mobile Lab) AppleWebKit/537.36 Mobile",
)
pg_m = ctx_manual.new_page()
pg_m.goto(f"{base_url}/")
m_obs = pg_m.evaluate(
"() => ({w: window.innerWidth, h: window.innerHeight, dpr: window.devicePixelRatio,"
" uaCustom: navigator.userAgent.includes('Custom Mobile Lab'), touch: navigator.maxTouchPoints > 0})"
)
ctx_manual.close()
exp1 = {
"iphone15": {"w": ip15["viewport"]["width"], "h": ip15["viewport"]["height"], "dpr": ip15["device_scale_factor"], "uaHasIPhone": True, "touch": True},
"pixel7": {"w": px7["viewport"]["width"], "h": px7["viewport"]["height"], "dpr": px7["device_scale_factor"], "uaHasPixel7": True, "touch": True},
"manual": {"w": 375, "h": 812, "dpr": 3, "uaCustom": True, "touch": True},
}
act1 = {"iphone15": ip_obs, "pixel7": px_obs, "manual": m_obs}
cases.append(dict(name="device_and_viewport_emulation", expected=exp1, actual=act1, passed=act1 == exp1))
# Case 2: Geolocation & Permissions grant/clear
ctx_geo = browser.new_context()
ctx_geo.grant_permissions(["geolocation", "notifications"])
ctx_geo.set_geolocation({"latitude": 39.9042, "longitude": 116.4074})
pg_geo = ctx_geo.new_page()
pg_geo.goto(f"{base_url}/map")
coords = pg_geo.evaluate(
"() => new Promise((res, rej) => navigator.geolocation.getCurrentPosition("
" pos => res([Number(pos.coords.latitude.toFixed(4)), Number(pos.coords.longitude.toFixed(4))]),"
" err => rej(err.message)))"
)
perm_before = pg_geo.evaluate(
"async () => ({geo: (await navigator.permissions.query({name: 'geolocation'})).state, notif: Notification.permission})"
)
ctx_geo.clear_permissions()
perm_after = pg_geo.evaluate(
"async () => (await navigator.permissions.query({name: 'geolocation'})).state"
)
ctx_geo.close()
exp2 = {"coords": [39.9042, 116.4074], "perm_before": {"geo": "granted", "notif": "granted"}, "perm_after": "prompt"}
act2 = {"coords": coords, "perm_before": perm_before, "perm_after": perm_after}
cases.append(dict(name="geolocation_and_permissions", expected=exp2, actual=act2, passed=act2 == exp2))
# Case 3: Locale, timezone, color scheme, and offline toggle
ctx_zh = browser.new_context(locale="zh-CN", timezone_id="Asia/Shanghai", color_scheme="dark")
pg_zh = ctx_zh.new_page()
pg_zh.goto(f"{base_url}/")
zh_obs = pg_zh.evaluate(
"() => ({lang: navigator.language, tz: Intl.DateTimeFormat().resolvedOptions().timeZone,"
" dark: window.matchMedia('(prefers-color-scheme: dark)').matches,"
" bg: getComputedStyle(document.body).backgroundColor})"
)
ctx_zh.set_offline(True)
offline_online_flag = pg_zh.evaluate("() => navigator.onLine")
offline_fetch_failed = pg_zh.evaluate(
"async () => { try { await fetch('/api/ping'); return false; } catch (e) { return true; } }"
)
ctx_zh.set_offline(False)
restored_online_flag = pg_zh.evaluate("() => navigator.onLine")
ctx_zh.close()
ctx_en = browser.new_context(locale="en-US", timezone_id="America/New_York", color_scheme="light")
pg_en = ctx_en.new_page()
pg_en.goto(f"{base_url}/")
en_obs = pg_en.evaluate(
"() => ({lang: navigator.language, tz: Intl.DateTimeFormat().resolvedOptions().timeZone,"
" dark: window.matchMedia('(prefers-color-scheme: dark)').matches})"
)
ctx_en.close()
exp3 = {
"zh_dark": {"lang": "zh-CN", "tz": "Asia/Shanghai", "dark": True, "bg": "rgb(18, 18, 18)"},
"en_light": {"lang": "en-US", "tz": "America/New_York", "dark": False},
"offline_flag": False,
"offline_fetch_failed": True,
"restored_online_flag": True,
}
act3 = {
"zh_dark": zh_obs,
"en_light": en_obs,
"offline_flag": offline_online_flag,
"offline_fetch_failed": offline_fetch_failed,
"restored_online_flag": restored_online_flag,
}
cases.append(dict(name="locale_timezone_color_scheme_and_offline", expected=exp3, actual=act3, passed=act3 == exp3))
# Case 4: Cookie CRUD + httpOnly visibility check
ctx_ck = browser.new_context()
ctx_ck.add_cookies([
{
"name": "app_session",
"value": "token_abc123",
"domain": "127.0.0.1",
"path": "/",
"httpOnly": True,
"secure": False,
"sameSite": "Lax",
},
{
"name": "theme_pref",
"value": "dark",
"domain": "127.0.0.1",
"path": "/",
"httpOnly": False,
"secure": False,
"sameSite": "Strict",
},
])
pg_ck = ctx_ck.new_page()
pg_ck.goto(f"{base_url}/")
all_ck = ctx_ck.cookies()
url_ck = ctx_ck.cookies(base_url)
js_cookie = pg_ck.evaluate("() => document.cookie")
sent_header = _Handler.last_cookie_header
ctx_ck.clear_cookies()
after_clear = len(ctx_ck.cookies())
ctx_ck.close()
exp4 = {
"total_added": 2,
"url_matched": 2,
"httponly_hidden_in_js": True,
"js_sees_theme_pref": True,
"server_received_both": True,
"after_clear": 0,
}
act4 = {
"total_added": len(all_ck),
"url_matched": len(url_ck),
"httponly_hidden_in_js": "app_session" not in js_cookie,
"js_sees_theme_pref": "theme_pref=dark" in js_cookie,
"server_received_both": ("app_session=token_abc123" in sent_header and "theme_pref=dark" in sent_header),
"after_clear": after_clear,
}
cases.append(dict(name="cookie_crud_operations", expected=exp4, actual=act4, passed=act4 == exp4))
# Case 5: localStorage & sessionStorage operations + pre-goto init seeding
ctx_st = browser.new_context()
ctx_st.add_init_script("localStorage.setItem('preload_key', 'ready_before_load');")
pg_st = ctx_st.new_page()
pg_st.goto(f"{base_url}/")
preload_dom = pg_st.locator("#preload-storage").text_content()
pg_st.evaluate("() => { localStorage.setItem('app_key', 'app_value'); sessionStorage.setItem('tab_id', 't-01'); }")
ls_val = pg_st.evaluate("() => localStorage.getItem('app_key')")
ss_val = pg_st.evaluate("() => sessionStorage.getItem('tab_id')")
pg_st.evaluate("() => { localStorage.clear(); sessionStorage.clear(); }")
after_ls = pg_st.evaluate("() => localStorage.length")
after_ss = pg_st.evaluate("() => sessionStorage.length")
ctx_st.close()
exp5 = {
"preload_dom": "ready_before_load",
"ls_val": "app_value",
"ss_val": "t-01",
"after_clear": [0, 0],
}
act5 = {
"preload_dom": preload_dom,
"ls_val": ls_val,
"ss_val": ss_val,
"after_clear": [after_ls, after_ss],
}
cases.append(dict(name="storage_operations_and_pre_goto_seed", expected=exp5, actual=act5, passed=act5 == exp5))
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
context.addCookies() 直接写入浏览器上下文的 Cookie 存储并按 domain/path 绑定目标源;而未导航前页面停留在 about:blank,直接执行 localStorage 会触发安全源限制,借助 addInitScript() 或 storageState 可在目标源文档脚本执行前安全注入。