Playwright Python 学习指南
本指南基于 Playwright Python 版本,整理了从入门到进阶的完整学习资料。 最后更新:2026年5月
目录
1. 简介与对比
什么是 Playwright?

Playwright 是由 Microsoft 开发的端到端(E2E)测试框架,用于现代 Web 应用程序。它支持:
- 跨浏览器测试:Chromium、WebKit、Firefox
- 跨平台:Windows、Linux、macOS
- 多语言支持:Node.js、Python、Java、.NET
- 移动模拟:Chrome (Android) 和 Mobile Safari 的原生移动模拟
Playwright vs 其他工具
| 特性 | Playwright | Puppeteer | Selenium |
|---|---|---|---|
| 浏览器支持 | Chromium, WebKit, Firefox | 仅 Chromium | 多浏览器 |
| Python 支持 | ✅ 原生支持 | ❌ 仅 Node.js | ✅ |
| 并行测试 | 原生支持 | 需要额外配置 | 需要额外配置 |
| 网络拦截 | 强大且灵活 | 基础支持 | 有限支持 |
| 移动模拟 | 原生支持 | 有限支持 | 有限支持 |
| 自动等待 | 内置 | 需要手动处理 | 需要显式等待 |
| Trace Viewer | 内置 | 无 | 无 |
| 测试运行器 | Pytest 插件 | 无 | 需要额外框架 |
Playwright Python 的优势:
- 同步和异步 API 支持
- 与 Pytest 深度集成
- 更强大的自动等待机制
- 优秀的调试工具(Trace Viewer)
- 支持 API 测试
2. 环境搭建
系统要求
- Python:3.8 或更高版本
- Windows:Windows 11+、Windows Server 2019+ 或 WSL
- macOS:macOS 14 (Sonoma) 或更高版本
- Linux:Debian 12/13、Ubuntu 22.04/24.04
安装步骤
使用 pip(推荐)
bash
# 安装 Pytest 插件
pip install pytest-playwright
# 安装浏览器
playwright install使用 Anaconda
bash
conda config --add channels conda-forge
conda config --add channels microsoft
conda install pytest-playwright项目结构
安装完成后,创建以下文件结构:
your_project/
├── tests/
│ ├── test_example.py # 测试文件
│ └── conftest.py # Pytest 配置(可选)
├── playwright/
│ └── .auth/ # 认证状态存储(建议加入 .gitignore)
└── pytest.ini # Pytest 配置(可选)更新 Playwright
bash
# 更新到最新版本
pip install pytest-playwright playwright -U
# 更新浏览器
playwright install
# 检查版本
playwright --version3. 核心概念
浏览器、上下文和页面
Playwright 采用三层架构:
Browser(浏览器)
└── BrowserContext(浏览器上下文)
└── Page(页面)- Browser:浏览器实例(如 Chromium、Firefox)
- BrowserContext:隔离的浏览器环境,类似于无痕模式
- Page:单个标签页或页面
测试隔离(Pytest Fixtures)
Pytest 插件提供了内置的 fixtures,每个测试都在独立的 BrowserContext 中运行:
python
from playwright.sync_api import Page
def test_example_test(page: Page):
# "page" 属于为此特定测试创建的隔离 BrowserContext
pass
def test_another_test(page: Page):
# 这个测试中的 "page" 与第一个测试完全隔离
pass常用 Fixtures
| Fixture | 作用域 | 说明 |
|---|---|---|
playwright | session | Playwright 实例 |
browser | session | 浏览器实例 |
context | function | 浏览器上下文(每个测试隔离) |
page | function | 页面对象(每个测试隔离) |
browser_name | session | 浏览器名称(chromium/firefox/webkit) |
使用 Fixtures 执行前后置操作
python
import pytest
from playwright.sync_api import Page, expect
@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
print("before the test runs")
# 每个测试前导航到起始 URL
page.goto("https://playwright.dev/")
yield
print("after the test runs")
def test_main_navigation(page: Page):
expect(page).to_have_url("https://playwright.dev/")定位器(Locators)
定位器是 Playwright 自动等待和重试机制的核心。推荐的定位器优先级:
page.get_by_role()- 通过可访问性属性定位(推荐)page.get_by_text()- 通过文本内容定位page.get_by_label()- 通过关联的标签文本定位表单控件page.get_by_placeholder()- 通过占位符定位输入框page.get_by_alt_text()- 通过替代文本定位(通常是图片)page.get_by_title()- 通过 title 属性定位page.get_by_test_id()- 通过data-testid属性定位
python
# 推荐:使用 role 定位器
page.get_by_role("button", name="Sign in").click()
# 使用文本定位
page.get_by_text("Welcome, John").click()
# 使用标签定位表单
page.get_by_label("Password").fill("secret")
# 使用 test id 定位
page.get_by_test_id("directions").click()自动等待
Playwright 在执行每个操作前会自动等待元素满足可操作性条件:
- 元素可见
- 元素稳定(不在动画中)
- 元素已启用
- 元素可以接收事件
python
# Playwright 会自动等待按钮可点击
page.get_by_role("button", name="Submit").click()4. 常用操作
页面导航
python
# 导航到 URL
page.goto("https://playwright.dev/")
# 等待页面加载完成(默认等待 load 事件)
page.goto("https://playwright.dev/", wait_until="networkidle")
# 导航到相对路径
page.goto("/login")元素交互
python
# 点击元素
page.get_by_role("button", name="Click me").click()
# 填写输入框
page.get_by_label("Username").fill("john")
# 勾选复选框
page.get_by_role("checkbox", name="Subscribe").check()
# 取消勾选
page.get_by_role("checkbox", name="Subscribe").uncheck()
# 选择下拉选项
page.get_by_role("combobox").select_option("value")
# 悬停
page.get_by_text("Menu").hover()
# 按键
page.get_by_role("textbox").press("Enter")
# 上传文件
page.get_by_label("Upload").set_input_files("file.pdf")
# 聚焦元素
page.get_by_label("Username").focus()截图
python
# 页面截图
page.screenshot(path="screenshot.png")
# 全页面截图(包括滚动区域)
page.screenshot(path="screenshot.png", full_page=True)
# 元素截图
page.locator(".header").screenshot(path="header.png")
# 获取截图字节数据
screenshot_bytes = page.screenshot()网络拦截
监听网络请求
python
# 监听请求和响应
page.on("request", lambda request: print(">>", request.method, request.url))
page.on("response", lambda response: print("<<", response.status, response.url))
# 等待特定响应
with page.expect_response("**/api/fetch_data") as response_info:
page.get_by_text("Update").click()
response = response_info.value拦截和模拟请求
python
# 模拟 API 响应
page.route("**/api/fetch_data", lambda route: route.fulfill(
status=200,
body=test_data,
))
# 阻止请求(如阻止图片加载)
page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
# 修改请求头
def handle_route(route):
headers = route.request.headers
del headers["x-secret"]
route.continue_(headers=headers)
page.route("**/*", handle_route)
# 修改响应
def handle_route(route):
response = route.fetch()
body = response.text()
body = body.replace("<title>", "<title>My prefix:")
route.fulfill(
response=response,
body=body,
headers={**response.headers, "content-type": "text/html"},
)
page.route("**/title.html", handle_route)录屏
python
# 在配置中启用录屏
# conftest.py 或 pytest.ini
# playwright_video_dir = "videos"
# 手动获取视频路径
page = context.new_page()
video = page.video
# 测试结束后获取路径
video_path = video.path()5. 进阶主题
API 测试
Playwright 可以直接测试 REST API,无需加载页面。
python
import os
from typing import Generator
import pytest
from playwright.sync_api import Playwright, APIRequestContext
GITHUB_API_TOKEN = os.getenv("GITHUB_API_TOKEN")
assert GITHUB_API_TOKEN, "GITHUB_API_TOKEN is not set"
@pytest.fixture(scope="session")
def api_request_context(
playwright: Playwright,
) -> Generator[APIRequestContext, None, None]:
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": f"token {GITHUB_API_TOKEN}",
}
request_context = playwright.request.new_context(
base_url="https://api.github.com", extra_http_headers=headers
)
yield request_context
request_context.dispose()
def test_should_create_bug_report(api_request_context: APIRequestContext) -> None:
data = {
"title": "[Bug] report 1",
"body": "Bug description",
}
new_issue = api_request_context.post(
"/repos/USER/REPO/issues", data=data
)
assert new_issue.ok
issues = api_request_context.get("/repos/USER/REPO/issues")
assert issues.ok
issues_response = issues.json()
issue = list(filter(lambda i: i["title"] == "[Bug] report 1", issues_response))[0]
assert issue
assert issue["body"] == "Bug description"Setup 和 Teardown
python
@pytest.fixture(scope="session", autouse=True)
def create_test_repository(
api_request_context: APIRequestContext,
) -> Generator[None, None, None]:
# Before all - 创建测试仓库
new_repo = api_request_context.post("/user/repos", data={"name": GITHUB_REPO})
assert new_repo.ok
yield
# After all - 删除测试仓库
deleted_repo = api_request_context.delete(f"/repos/{GITHUB_USER}/{GITHUB_REPO}")
assert deleted_repo.ok认证状态复用
基础方案:保存和加载认证状态
python
# 登录并保存状态
page = context.new_page()
page.goto("https://github.com/login")
page.get_by_label("Username or email address").fill("username")
page.get_by_label("Password").fill("password")
page.get_by_role("button", name="Sign in").click()
# 保存存储状态到文件
context.storage_state(path="playwright/.auth/user.json")
# 在新上下文中加载状态
context = browser.new_context(storage_state="playwright/.auth/user.json")使用 Pytest Fixture 实现认证复用
python
# conftest.py
import pytest
from playwright.sync_api import Browser, BrowserContext
@pytest.fixture(scope="session")
def authenticated_context(browser: Browser) -> BrowserContext:
# 创建上下文并执行登录
context = browser.new_context()
page = context.new_page()
page.goto("https://github.com/login")
page.get_by_label("Username").fill("username")
page.get_by_label("Password").fill("password")
page.get_by_role("button", name="Sign in").click()
page.wait_for_url("https://github.com/")
# 保存状态
context.storage_state(path="playwright/.auth/user.json")
yield context
context.close()
@pytest.fixture
def page(authenticated_context: BrowserContext):
# 每个测试使用已认证的上下文
page = authenticated_context.new_page()
yield page
page.close()高级方案:使用 API 请求进行认证
python
# conftest.py
@pytest.fixture(scope="session")
def api_request_context(playwright: Playwright) -> Generator[APIRequestContext, None, None]:
context = playwright.request.new_context(
http_credentials={"username": "test", "password": "test"}
)
context.get("https://api.example.com/login")
yield context
context.dispose()CI/CD 集成
GitHub Actions 配置示例
yaml
# .github/workflows/playwright.yml
name: Playwright Tests
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dependencies
run: |
pip install pytest-playwright playwright
playwright install --with-deps
- name: Run Playwright tests
run: pytest
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-report
path: playwright-report/
retention-days: 30CI 最佳实践
- 使用 Linux 运行器:更便宜且更快
- 并行测试:使用
pytest-xdist加速 - 优化浏览器下载:只安装需要的浏览器
- 使用 Trace Viewer:调试 CI 失败的测试
bash
# 只安装 Chromium
playwright install chromium
# 使用 xdist 并行运行
pip install pytest-xdist
pytest -n autoTrace Viewer
Trace Viewer 是一个 GUI 工具,用于探索记录的 Playwright 跟踪信息。
记录跟踪
python
# 在代码中启动跟踪
context = browser.new_context()
context.tracing.start(screenshots=True, snapshots=True)
page = context.new_page()
page.goto("https://playwright.dev/")
# 停止跟踪并保存
context.tracing.stop(path="trace.zip")使用 Pytest 配置跟踪
python
# conftest.py
@pytest.fixture(autouse=True)
def configure_tracing(context):
context.tracing.start(screenshots=True, snapshots=True)
yield
# 只在测试失败时保存跟踪
if sys.exc_info()[0] is not None:
context.tracing.stop(path=f"trace-{test_name}.zip")
else:
context.tracing.stop()查看跟踪
bash
# 使用 CLI 打开
playwright show-trace trace.zip
# 或访问 https://trace.playwright.devTrace Viewer 功能
- Actions:查看每个操作使用的定位器和执行时间
- Screenshots:查看测试执行的屏幕截图
- Snapshots:查看每个操作前后的 DOM 快照
- Console:查看浏览器控制台日志
- Network:查看网络请求
- Source:查看源代码位置
测试断言
Playwright 提供了丰富的断言(需要使用 expect):
python
from playwright.sync_api import expect
def test_assertions_example(page: Page):
page.goto("https://playwright.dev/")
# 页面断言
expect(page).to_have_title(re.compile("Playwright"))
expect(page).to_have_url("https://playwright.dev/")
# 元素断言
expect(page.get_by_text("Welcome")).to_be_visible()
expect(page.get_by_role("button")).to_be_enabled()
expect(page.get_by_role("checkbox")).to_be_checked()
expect(page.get_by_text("Hello")).to_contain_text("Hello")
expect(page.get_by_role("link")).to_have_attribute("href", "/about")
# 列表断言
expect(page.get_by_role("listitem")).to_have_count(3)
expect(page.get_by_role("listitem")).to_have_text(["apple", "banana", "orange"])
# 输入框断言
expect(page.get_by_label("Username")).to_have_value("john")软断言
软断言不会立即终止测试执行,而是在测试结束时显示所有失败的断言:
python
def test_soft_assertions(page: Page):
expect(page.get_by_test_id("status")).to_have_text("Success") # 软断言
page.get_by_role("link", name="next page").click()6. 实践经验与踩坑记录
本章节整理了实际项目中使用 Playwright Python 的经验教训、常见问题和边界情况。
6.1 定位器(Locators)的坑
坑 1:get_by_text() 的部分匹配问题
python
# ❌ 错误:会匹配到任何包含 "Save" 的元素,包括 "Save Draft"、"Save and Continue"
page.get_by_text("Save").click()
# ✅ 正确:使用 exact=True 进行精确匹配
page.get_by_text("Save", exact=True).click()
# ✅ 或者使用正则表达式
page.get_by_text(re.compile(r"^Save$")).click()注意事项:
get_by_text()默认是部分匹配(substring match)- 文本匹配会自动规范化空白字符(多个空格变一个,换行变空格)
- 如果页面有多个匹配元素,会抛出
strict mode violation错误
坑 2:get_by_role() 的 name 匹配
python
# ❌ 错误:name 参数是精确匹配,不会匹配部分文本
page.get_by_role("button", name="Submit").click() # 不会匹配 "Submit Form"
# ✅ 使用正则表达式进行模糊匹配
page.get_by_role("button", name=re.compile("Submit", re.IGNORECASE)).click()
# ✅ 或者使用 get_by_text() 作为备选
page.get_by_role("button").filter(has_text="Submit").click()坑 3:动态 ID 和动态文本
python
# ❌ 错误:使用动态生成的 ID
page.locator("#el-12345").click() # ID 每次加载都可能变化
# ✅ 正确:使用 data-testid 或稳定的选择器
page.get_by_test_id("submit-button").click()
# ✅ 或者使用 role + text 组合
page.get_by_role("button", name="Submit").click()坑 4:Shadow DOM 中的定位
python
# ✅ Playwright 默认可以穿透 Shadow DOM
page.get_by_text("Details").click() # 可以直接定位 shadow DOM 内的元素
# ❌ 但 XPath 不能穿透 Shadow DOM
page.locator("xpath=//div[@id='inner-details']").click() # 会失败
# ✅ CSS 选择器可以穿透
page.locator("x-details #inner-details").click()坑 5:iframe 中的定位
python
# ❌ 错误:直接定位 iframe 内的元素
page.get_by_text("iframe content").click() # 找不到
# ✅ 正确:先切换到 iframe
frame = page.frame_locator("iframe#my-frame")
frame.get_by_text("iframe content").click()
# ✅ 或者使用 locator 内的 frame_locator
page.locator("iframe#my-frame").content_frame().get_by_text("content").click()6.2 自动等待的坑
坑 1:元素被遮挡
python
# 场景:有一个 loading 遮罩层覆盖了按钮
# ❌ 会超时失败,因为按钮被遮挡,无法接收事件
page.get_by_role("button", name="Submit").click()
# ✅ 方案 1:等待遮罩层消失
page.get_by_role("button", name="Submit").click(force=True) # 强制点击,跳过检查
# ✅ 方案 2:等待遮罩层消失后再点击
expect(page.locator(".loading-overlay")).to_be_hidden()
page.get_by_role("button", name="Submit").click()
# ✅ 方案 3:使用 timeout 参数增加等待时间
page.get_by_role("button", name="Submit").click(timeout=60000) # 60秒坑 2:元素在动画中
python
# 场景:元素有 CSS 动画,Playwright 会等待动画完成
# ❌ 可能会超时,如果动画持续时间很长
page.get_by_role("button").click()
# ✅ 方案 1:禁用 CSS 动画(通过注入样式)
page.add_style_tag(content="* { animation: none !important; transition: none !important; }")
# ✅ 方案 2:使用 force 跳过稳定性检查
page.get_by_role("button").click(force=True)坑 3:opacity:0 的元素
python
# ❌ 误解:opacity:0 的元素被认为是"可见的"
# 这是 Playwright 的设计:opacity:0 的元素仍然可以接收事件
expect(page.locator(".invisible-element")).to_be_visible() # 会通过!
# ✅ 如果需要检查真正的可见性,使用 bounding box
element = page.locator(".element")
box = element.bounding_box()
assert box is not None and box["width"] > 0 and box["height"] > 0坑 4:display:none vs visibility:hidden
python
# display:none - 元素不存在于布局中,不可见
# visibility:hidden - 元素占据空间,但不可见
# 两者都被认为是"不可见的"
expect(page.locator("[style*='display:none']")).to_be_hidden() # ✅
expect(page.locator("[style*='visibility:hidden']")).to_be_hidden() # ✅6.3 网络拦截的坑
坑 1:拦截顺序问题
python
# ❌ 错误:后注册的路由会覆盖先注册的
page.route("**/api/data", lambda route: route.fulfill(status=200, body="response1"))
page.route("**/api/data", lambda route: route.fulfill(status=200, body="response2"))
# 最终会使用 response2
# ✅ 正确:使用 page.unroute() 取消之前的路由
page.route("**/api/data", lambda route: route.fulfill(status=200, body="response1"))
page.unroute("**/api/data")
page.route("**/api/data", lambda route: route.fulfill(status=200, body="response2"))坑 2:glob 模式匹配
python
# ❌ 错误:glob 模式必须匹配完整 URL
page.route("api/data", handler) # 不会匹配 https://example.com/api/data
# ✅ 正确:使用 ** 通配符
page.route("**/api/data", handler)
page.route("https://example.com/api/data", handler)
# glob 模式说明:
# * - 匹配除 / 外的任意字符
# ** - 匹配任意字符(包括 /)
# ? - 匹配 ? 字符本身坑 3:Service Worker 干扰
python
# 场景:使用了 Mock Service Worker (MSW) 等工具
# ❌ 问题:Service Worker 会拦截请求,导致 Playwright 的 route() 失效
# ✅ 方案:禁用 Service Workers
context = browser.new_context(
service_workers="block"
)坑 4:异步请求的时序
python
# ❌ 错误:没有等待异步请求完成
page.route("**/api/data", lambda route: route.fulfill(status=200, body="mock"))
page.get_by_text("Load Data").click()
# 页面可能还没来得及发起请求
# ✅ 正确:使用 expect_response 等待请求
with page.expect_response("**/api/data") as response_info:
page.get_by_text("Load Data").click()
response = response_info.value
assert response.json() == expected_data6.4 认证状态复用的坑
坑 1:storage_state 不包含 sessionStorage
python
# ❌ 误解:storage_state() 会保存所有存储
# 实际上:只保存 cookies、localStorage 和 IndexedDB
# sessionStorage 不会被保存!
# ✅ 如果需要保存 sessionStorage,需要手动处理
session_storage = page.evaluate("() => JSON.stringify(sessionStorage)")
# 保存到文件或变量
# 然后在新页面中恢复
page.evaluate("""(storage) => {
const entries = JSON.parse(storage);
for (const [key, value] of Object.entries(entries)) {
window.sessionStorage.setItem(key, value);
}
}""", session_storage)坑 2:token 过期处理
python
# 场景:认证 token 会在一定时间后过期
# ❌ 错误:直接使用保存的 state,可能已过期
context = browser.new_context(storage_state="state.json")
# ✅ 正确:在 fixture 中添加 token 刷新逻辑
@pytest.fixture
def authenticated_page(page, browser):
# 尝试使用保存的状态
try:
context = browser.new_context(storage_state="state.json")
test_page = context.new_page()
test_page.goto("/dashboard")
# 检查是否仍然有效
if test_page.url.includes("/login"):
raise Exception("Token expired")
yield test_page
except:
# 重新登录
context = browser.new_context()
test_page = context.new_page()
# ... 登录逻辑 ...
context.storage_state(path="state.json")
yield test_page坑 3:多环境的 state 文件
python
# ❌ 错误:不同环境使用同一个 state 文件
# 开发环境和生产环境的 cookies 可能冲突
# ✅ 正确:为每个环境使用不同的 state 文件
@pytest.fixture
def state_file(request):
env = request.config.getoption("--env", default="dev")
return f"playwright/.auth/{env}/user.json"6.5 CI/CD 集成的坑
坑 1:浏览器安装失败
bash
# ❌ 问题:CI 环境缺少系统依赖
playwright install chromium
# ✅ 正确:安装浏览器及其依赖
playwright install --with-deps chromium
# ✅ 或者在 GitHub Actions 中使用官方 action
- uses: microsoft/playwright-github-action@v1坑 2:测试超时
python
# ❌ 问题:CI 环境比本地慢,容易超时
def test_slow(page: Page):
page.goto("https://example.com") # 默认超时 30 秒
# ✅ 方案 1:增加全局超时
# conftest.py
@pytest.fixture(autouse=True)
def set_timeout(page: Page):
page.set_default_timeout(60000) # 60 秒
# ✅ 方案 2:在 pytest.ini 中配置
# pytest.ini
# [pytest]
# timeout = 120
# ✅ 方案 3:对特定操作增加超时
page.goto("https://example.com", timeout=60000)坑 3:并行测试的资源冲突
python
# ❌ 问题:并行测试时共享资源会冲突
# 例如:两个测试同时写入同一个文件
# ✅ 方案 1:使用独立的测试数据
@pytest.fixture
def unique_user():
import uuid
return f"test-user-{uuid.uuid4()}"
# ✅ 方案 2:使用 pytest-xdist 的 worker_id
@pytest.fixture
def test_data(worker_id):
return f"data-{worker_id}"坑 4:截图和视频的存储
python
# ❌ 问题:CI 环境中截图路径可能不存在
# ✅ 正确:确保目录存在
import os
os.makedirs("test-results", exist_ok=True)
# ✅ 或者在 conftest.py 中配置
@pytest.fixture(autouse=True)
def setup_test_dir():
os.makedirs("test-results", exist_ok=True)6.6 无法实现或有难度的场景
场景 1:原生文件对话框
python
# ❌ 无法直接操作系统的原生文件对话框
# Playwright 只能处理 HTML 的文件输入
# ✅ 替代方案:使用 set_input_files()
page.get_by_label("Upload").set_input_files("path/to/file.pdf")
# ✅ 或者使用 file_chooser 事件
with page.expect_file_chooser() as fc_info:
page.get_by_text("Upload").click()
file_chooser = fc_info.value
file_chooser.set_files("path/to/file.pdf")场景 2:原生弹窗(alert/confirm/prompt)
python
# ✅ 可以处理,但需要预先注册对话框处理器
page.on("dialog", lambda dialog: dialog.accept())
# 或者
page.on("dialog", lambda dialog: dialog.dismiss())
# ❌ 不能在对话框出现后才注册处理器
# 必须在触发对话框的操作之前注册场景 3:Canvas 和 WebGL
python
# ❌ 无法直接操作 Canvas 内部的元素
# Canvas 是一个位图,Playwright 看不到内部结构
# ✅ 替代方案:
# 1. 截图对比
expect(page.locator("canvas")).to_have_screenshot("expected.png")
# 2. 通过 JavaScript 与 Canvas 交互
page.evaluate("canvas.getContext('2d').fillRect(0, 0, 100, 100)")
# 3. 如果应用提供了无障碍属性,可以使用那些场景 4:视频播放器
python
# ❌ 无法直接控制 HTML5 视频播放器的播放进度
# ✅ 替代方案:通过 JavaScript 控制
page.evaluate("document.querySelector('video').currentTime = 30")
page.evaluate("document.querySelector('video').play()")
page.evaluate("document.querySelector('video').pause()")场景 5:拖放排序
python
# ✅ 基本拖放支持
source = page.locator("#draggable")
target = page.locator("#droppable")
source.drag_to(target)
# ❌ 但某些复杂的拖放库(如 react-beautiful-dnd)可能需要特殊处理
# 可能需要模拟鼠标事件序列
source.drag_to(target, source_position={"x": 0, "y": 0}, target_position={"x": 0, "y": 0})场景 6:多标签页交互
python
# ✅ 可以处理多个标签页
with context.expect_page() as new_page_info:
page.get_by_text("Open New Tab").click()
new_page = new_page_info.value
new_page.get_by_text("Content").click()
# ❌ 但需要注意:每个 page 有自己的上下文
# 不能直接在两个 page 之间共享变量(除了通过 context)场景 7:WebSocket 测试
python
# ✅ 可以监听 WebSocket 消息
page.on("websocket", lambda ws: ws.on("framereceived", lambda data: print(data)))
# ❌ 但 WebSocket 消息的时序很难控制
# 建议:使用 mock 或等待特定消息6.7 性能优化建议
建议 1:复用浏览器上下文
python
# ❌ 错误:每个测试都创建新的浏览器实例
def test_one():
browser = playwright.chromium.launch()
page = browser.new_page()
# ...
browser.close()
# ✅ 正确:使用 session 级别的 fixture 复用浏览器
@pytest.fixture(scope="session")
def browser(playwright):
browser = playwright.chromium.launch()
yield browser
browser.close()建议 2:减少不必要的等待
python
# ❌ 错误:使用 time.sleep()
time.sleep(5) # 固定等待,不可靠
# ✅ 正确:使用 Playwright 的等待机制
page.wait_for_selector("#element")
page.wait_for_load_state("networkidle")
expect(page.get_by_text("Loaded")).to_be_visible()建议 3:并行测试配置
python
# pytest.ini
[pytest]
# 使用 pytest-xdist 进行并行测试
# pytest -n auto # 自动检测 CPU 核心数
# pytest -n 4 # 使用 4 个 worker
addopts = -n auto建议 4:只在失败时记录 Trace
python
# ❌ 错误:始终记录 trace(性能开销大)
context.tracing.start(screenshots=True, snapshots=True)
# ✅ 正确:只在失败时记录
@pytest.fixture(autouse=True)
def auto_trace(context, request):
context.tracing.start(screenshots=True, snapshots=True)
yield
if request.node.rep_call.failed:
context.tracing.stop(path=f"trace-{request.node.name}.zip")
else:
context.tracing.stop()6.8 调试技巧
技巧 1:使用 page.pause() 设置断点
python
def test_debug(page: Page):
page.goto("https://example.com")
page.pause() # 会打开 Playwright Inspector
page.get_by_text("Click me").click()技巧 2:使用 PWDEBUG 环境变量
bash
# 打开 Playwright Inspector
PWDEBUG=1 pytest -s tests/test_example.py
# 打开浏览器开发者工具
PWDEBUG=console pytest -s tests/test_example.py技巧 3:使用 DEBUG 环境变量查看详细日志
bash
# 查看 Playwright API 调用日志
DEBUG=pw:api pytest -s tests/test_example.py
# 查看所有日志
DEBUG=pw:* pytest -s tests/test_example.py技巧 4:截图调试
python
def test_with_screenshot(page: Page):
page.goto("https://example.com")
page.screenshot(path="debug-1.png") # 在关键步骤截图
page.get_by_text("Click").click()
page.screenshot(path="debug-2.png")技巧 5:使用 headed 模式观察
python
# 在 conftest.py 中配置
@pytest.fixture
def browser_type_launch_args():
return {
"headless": False, # 显示浏览器窗口
"slow_mo": 500, # 每个操作延迟 500ms
}7. 学习资源
官方文档
- Playwright Python 官方文档
- Playwright Python API 参考
- Pytest 插件参考
- Playwright Python GitHub
- Playwright Release Notes
学习教程
社区资源
工具和扩展
示例项目
附录:常用命令
bash
# 运行所有测试
pytest
# 运行特定测试文件
pytest tests/test_example.py
# 运行特定测试函数
pytest tests/test_example.py::test_has_title
# 运行带界面的测试(有头模式)
pytest --headed
# 运行特定浏览器
pytest --browser chromium
pytest --browser firefox
pytest --browser webkit
# 运行多个浏览器
pytest --browser chromium --browser firefox
# 调试测试
pytest --debug
# 生成测试代码
playwright codegen playwright.dev
# 查看跟踪
playwright show-trace trace.zip
# 安装浏览器
playwright install
# 安装特定浏览器
playwright install chromium
playwright install firefox
playwright install webkit
# 安装浏览器依赖(CI 环境)
playwright install --with-deps附录:Pytest 配置示例
python
# conftest.py
import pytest
from playwright.sync_api import Playwright, Browser, BrowserContext, Page
@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
"""自定义浏览器上下文参数"""
return {
**browser_context_args,
"viewport": {
"width": 1920,
"height": 1080,
},
"ignore_https_errors": True,
}
@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
"""自定义浏览器启动参数"""
return {
**browser_type_launch_args,
"headless": True,
"slow_mo": 50, # 每个操作延迟 50ms,便于观察
}
@pytest.fixture(scope="session")
def browser_name():
"""指定默认浏览器"""
return "chromium"ini
# pytest.ini
[pytest]
# 测试目录
testpaths = tests
# 默认参数
addopts =
--browser chromium
--tracing on-first-retry
--screenshot only-on-failure
--video on-first-retry
# 标记
markers =
slow: marks tests as slow
smoke: marks tests as smoke tests参考资料来源: