Playwright 移动端测试
核对 Playwright 内置 devices 移动设备模拟、触摸事件边界、地理位置与权限授予、横竖屏视口切换及常见设备描述符清单,并附离线 Chromium 实测数据。
学完这一章,你能够
- 核对 Playwright 内置 devices 移动设备模拟、触摸事件边界、地理位置与权限授予、横竖屏视口切换及常见设备描述符清单,并附离线 Chromium 实测数据。
移动端设备模拟能力概述
Playwright 不仅支持桌面端自动化,还可在 PC 上模拟移动端浏览器环境,涵盖手机与平板的视口尺寸、设备像素比(`deviceScaleFactor`)及移动 User-Agent、触摸事件、GPS 地理位置和浏览器权限(地理位置、摄像头、麦克风、通知等),用于验证响应式布局与移动端交互。
借助内置 `devices` 描述符字典(Playwright 1.64.0 内置 `207` 项设备预设),只需将 `devices['iPhone 12']` 或 `devices['Pixel 5']` 展开传入 `browser.newContext()` 即可一键启用视口、`deviceScaleFactor`、移动端 UA、触摸支持及横竖屏参数。需留意:Playwright 预设的 `viewport` 扣除了移动端浏览器地址栏高度,本站离线实测加载 `iPhone 12` 测得 `window.innerWidth=390`、`innerHeight=664`、`devicePixelRatio=3` 且 UA 含 `iPhone`;加载 `Pixel 5` 测得 `393×727`、`devicePixelRatio=2.75` 且 `maxTouchPoints > 0`。
模拟触摸操作与 API 边界核实
在启用 `hasTouch: true`(或展开移动设备预设)的上下文中,可使用 `page.tap(selector)` / `locator.tap()` 轻点元素,或用 `page.touchscreen.tap(x, y)` 在指定视口坐标触发触摸事件。必须明确指出的是:Playwright 官方 `Touchscreen` 类原生仅提供 `tap(x, y)`(本站离线实测 `hasattr` 核实 `page.touchscreen` 仅含 `['tap']`,并无内置 `swipe()`、`down()` 或 `up()` 方法);若需模拟滑动或长按,应基于 `page.mouse`、派发自定义 `TouchEvent`/`PointerEvent` 或封装辅助函数实现。实测中 `page.tap('button#submit')` 顺序触发了 `touchstart` 与 `click`,`page.touchscreen.tap(48, 92)` 精确在目标触控区记录到坐标事件 `pad:48,92`。
模拟地理位置、权限控制与横竖屏切换
在 `browser.newContext()` 中同时传入 `geolocation: { longitude, latitude }` 与 `permissions: ['geolocation']`,即可向安全源页面(含本地回环 `127.0.0.1`)提供受控 GPS 坐标,运行中还可调用 `context.setGeolocation()` 动态更新位置。本站离线实测先设定北京坐标 `[39.9042, 116.4074]`,页面调用 `navigator.geolocation.getCurrentPosition()` 精确读回该坐标;随后动态切换为上海 `[31.2304, 121.4737]` 立即生效。
通过 `permissions` 数组(或运行时 `context.grantPermissions()`)可预先授予 `geolocation`、`camera`、`microphone`、`notifications` 等常见权限而不弹出拦截框。本站实测配置 `permissions=['geolocation', 'notifications']` 后,`navigator.permissions.query({name: 'geolocation'})` 与 `Notification.permission` 均返回 `granted`。
模拟横竖屏切换既可在新建上下文/页面时互换 `viewport` 的宽高(如竖屏 `375×812` 切为横屏 `812×375` 并保持 `isMobile: true`),也可在运行中调用 `page.setViewportSize()` 动态调整。本站实测初始 `375×812` 下 `matchMedia('(orientation: portrait)').matches` 为 `true`,调用 `set_viewport_size({width: 812, height: 375})` 后 `matchMedia('(orientation: landscape)').matches` 立即转为 `true`。
常用移动测试 API 与内置设备清单
以下五个速查表分别列出移动端测试核心配置/操作 API,以及 iPhone、Google Pixel、iPad 与其他 Android 机型的常见屏幕参数参考(注:表中尺寸为设备标称逻辑分辨率参考,Playwright 运行时部分设备描述符会针对浏览器工具栏扣减默认 `viewport.height`,且如 `iPhone SE`、`iPhone 12`、`Pixel 5`、`iPad (gen 6)`、`Galaxy S8` 等均已在本站离线环境 `playwright.devices` 中核实存在)。使用任何设备时只需按名称索引 `devices[name]` 并结合 `geolocation`/`permissions` 传入 `newContext()` 即可。
移动端测试常用 API 速查
| API | 说明 | 示例 |
|---|---|---|
| devices['iPhone 12'] | 按名称读取内置设备描述符 | const iphone = devices['iPhone 12'] |
| browser.newContext({ ...device }) | 以指定设备参数创建隔离上下文 | browser.newContext({ ...iPhone }) |
| page.tap(selector) / locator.tap() | 对目标元素派发触摸轻点(需 hasTouch) | await page.tap('#btn') |
| page.touchscreen.tap(x, y) | 在指定视口坐标触发触摸轻点 | await page.touchscreen.tap(100, 200) |
| 触摸按下(需自行封装/指针事件) | Playwright Touchscreen 原生仅提供 tap,长按需用指针事件或鼠标模拟 | 自定义封装或 dispatchEvent('touchstart') |
| 触摸抬起(需自行封装/指针事件) | Playwright Touchscreen 原生无 up(),需配合自定义触摸/指针结束事件 | 自定义封装或 dispatchEvent('touchend') |
| geolocation | 配置上下文模拟的经纬度坐标 | { longitude: 120, latitude: 30 } |
| permissions | 预授予浏览器敏感权限列表 | ['geolocation', 'notifications'] |
| viewport | 设置页面视口宽高(支持横竖屏切换) | { width: 812, height: 375 } |
| isMobile | 启用移动端 meta viewport 缩放与视口行为 | isMobile: true |
常见 iPhone 系列设备参数参考
| 设备名称 | 标称视口 | deviceScaleFactor | UA 类型 | 备注 |
|---|---|---|---|---|
| iPhone SE | 375 × 667 | 2 | Safari iOS | 小屏经典款 |
| iPhone 6 | 375 × 667 | 2 | Safari iOS | 旧款 |
| iPhone 7 | 375 × 667 | 2 | Safari iOS | 旧款 |
| iPhone 8 | 375 × 667 | 2 | Safari iOS | 常用 |
| iPhone 8 Plus | 414 × 736 | 3 | Safari iOS | 大屏 |
| iPhone X | 375 × 812 | 3 | Safari iOS | 刘海屏 |
| iPhone 11 | 414 × 896 | 2 | Safari iOS | 常用 |
| iPhone 11 Pro | 375 × 812 | 3 | Safari iOS | 常规 |
| iPhone 11 Pro Max | 414 × 896 | 3 | Safari iOS | 大屏 |
| iPhone 12 | 390 × 844(预设视口 390 × 664) | 3 | Safari iOS | 热门 |
| iPhone 12 Pro | 390 × 844 | 3 | Safari iOS | 常规 |
| iPhone 12 Pro Max | 428 × 926 | 3 | Safari iOS | 大屏 |
| iPhone 12 Mini | 360 × 780 | 3 | Safari iOS | 小屏 |
| iPhone 13 | 390 × 844 | 3 | Safari iOS | 热门 |
| iPhone 13 Pro | 390 × 844 | 3 | Safari iOS | 常规 |
| iPhone 13 Pro Max | 428 × 926 | 3 | Safari iOS | 大屏 |
| iPhone 13 Mini | 360 × 780 | 3 | Safari iOS | 小屏 |
常见 Google Pixel 系列设备参数参考
| 设备名称 | 标称视口 | deviceScaleFactor | UA 类型 | 备注 |
|---|---|---|---|---|
| Pixel 2 | 411 × 731 | 2.6 | Chrome Android | 旧款 |
| Pixel 2 XL | 411 × 823 | 3.5 | Chrome Android | 大屏 |
| Pixel 3 | 393 × 786 | 2.75 | Chrome Android | 常规 |
| Pixel 3 XL | 412 × 847 | 3.5 | Chrome Android | 大屏 |
| Pixel 4 | 353 × 745 | 2.75 | Chrome Android | 小屏 |
| Pixel 4 XL | 412 × 869 | 3.5 | Chrome Android | 大屏 |
| Pixel 5 | 393 × 851(预设视口 393 × 727) | 2.75 | Chrome Android | 推荐 |
常见 iPad 系列设备参数参考
| 设备名称 | 标称视口 | deviceScaleFactor | UA 类型 | 备注 |
|---|---|---|---|---|
| iPad (gen 6) | 768 × 1024 | 2 | Safari iOS | 常用 |
| iPad (gen 7) | 810 × 1080 | 2 | Safari iOS | 常规 |
| iPad Air | 820 × 1180 | 2 | Safari iOS | 中大屏 |
| iPad Mini | 768 × 1024 | 2 | Safari iOS | 小屏平板 |
| iPad Pro 11 | 834 × 1194 | 2 | Safari iOS | 专业屏 |
| iPad Pro 12.9 | 1024 × 1366 | 2 | Safari iOS | 大屏 |
其他常见 Android 机型参数参考
| 设备名称 | 标称视口 | deviceScaleFactor | UA 类型 | 备注 |
|---|---|---|---|---|
| Galaxy S5 | 360 × 640 | 3 | Chrome Android | 较老 |
| Galaxy S8 | 360 × 740 | 4 | Chrome Android | 常规 |
| Galaxy S9+ | 412 × 846 | 4.5 | Chrome Android | 高分屏 |
| Galaxy Note 3 | 360 × 640 | 3 | Chrome Android | 旧款 |
| Galaxy Note 9 | 414 × 846 | 4.5 | Chrome Android | 大屏 |
| Galaxy A51/71 | 412 × 914 | 2.63 | Chrome Android | 热门 |
离线 Chromium 实测设备描述符模拟、触摸点击、定位权限与横竖屏切换
"""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()
- 核对 iPhone 12(390×664, dpr=3)与 Pixel 5(393×727, dpr=2.75)模拟参数、page.tap 与 touchscreen.tap 触控事件、北京/上海定位坐标与权限 granted,以及 375×812 与 812×375 横竖屏媒体查询切换。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:122195a9b2bdfcfa2194a5d034f929459525cd862f45b6f304b199cd68e9ad75
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:3d679039e861b8afce8f48a239e1672e34eed8eb7f629eaeac5bf1208570a2b3
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在移动端模拟中,`devices['iPhone 12']` 在 Chromium 下运行与在真实 iOS Safari 上运行有何核心差异?
展开参考解答
Chromium 下的设备模拟可以高保真复现视口、`deviceScaleFactor`、触摸事件与移动端 UA,但底层渲染与 JS 引擎仍是 Blink/V8 而非 WebKit;若需核对 iOS Safari 专属排版或滚动差异,应配合 Playwright 的 WebKit 引擎甚至真机复测。