目录
简介
Playwright 是专为满足端到端测试需求而创建的。它支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。您可以在 Windows、Linux 和 macOS 上进行测试,无论是本地测试还是在持续集成(CI)环境中,都可以进行无头模式或有头模式测试,并原生支持移动端模拟。
Playwright 库可以用作通用的浏览器自动化工具,为同步和异步 Python 提供了一套强大的 API,用于自动化 Web 应用程序。
本简介介绍了 Playwright Pytest 插件,这是编写端到端测试推荐的方式。
您将学习
- 如何安装 Playwright Pytest
- 如何运行示例测试
安装 Playwright Pytest
Playwright 推荐使用官方的 Playwright Pytest 插件Playwright Pytest plugin来编写端到端测试。该插件提供了上下文隔离功能,并可直接在多种浏览器配置下运行测试。
首先,您需要安装 Playwright 并运行示例测试来查看它的实际效果。
安装 Pytest 插件:
pip install pytest-playwright
安装所需的浏览器:
playwright install
添加示例测试
在当前工作目录或子目录中创建一个遵循 test_
前缀约定的文件,例如 test_example.py
,并在其中添加以下代码。确保您的测试名称也遵循 test_
前缀约定。
# test_example.py
import re
from playwright.sync_api import Page, expect
def test_has_title(page: Page):
page.goto("https://playwright.dev/")
# Expect a title "to contain" a substring.
expect(page).to_have_title(re.compile("Playwright"))
def test_get_started_link(page: Page):
page.goto("https://playwright.dev/")
# Click the get started link.
page.get_by_role("link", name="Get started").click()
# Expects page to have a heading with the name of Installation.
expect(page.get_by_role("heading", name="Installation")).to_be_visible()
运行示例测试
默认情况下,测试将在 Chromium 上运行。这可以通过命令行选项进行配置。测试在无头模式下运行,意味着在运行测试时不会打开浏览器 UI。测试的结果和测试日志将在终端中显示。
pytest
更新 Playwright
要更新 Playwright 到最新版本,请运行以下命令:
pip install pytest-playwright playwright -U
系统需求
- Python 3.8 or higher.
- Windows 10+, Windows Server 2016+ or Windows Subsystem for Linux (WSL).
- macOS 13 Ventura, or macOS 14 Sonoma.
- Debian 11, Debian 12, Ubuntu 20.04 or Ubuntu 22.04, Ubuntu 24.04, on x86-64 and arm64 architecture.