安装
简介
Playwright 专门为满足端到端测试的需求而创建。Playwright 支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上,本地或在 CI 上,无头或有头地进行测试,并支持原生移动设备模拟。
Playwright 库可用作通用浏览器自动化工具,为同步和异步 Python 提供强大的 API 集来自动化 Web 应用程序。
本介绍描述了 Playwright Pytest 插件,这是编写端到端测试的推荐方式。
您将学到
安装 Playwright Pytest
Playwright 推荐使用官方的Playwright Pytest 插件来编写端到端测试。它提供了上下文隔离,并开箱即用地在多个浏览器配置上运行。
首先安装 Playwright 并运行示例测试以查看其效果。
- PyPI
- Anaconda
安装所需的浏览器
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.net.cn/")
# 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.net.cn/")
# 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 上运行。这可以通过CLI 选项进行配置。测试以无头模式运行,这意味着在运行测试时不会打开浏览器 UI。测试结果和测试日志将显示在终端中。
pytest
更新 Playwright
要将 Playwright 更新到最新版本,请运行以下命令
pip install pytest-playwright playwright -U
系统要求
- Python 3.8 或更高版本。
- Windows 10+、Windows Server 2016+ 或适用于 Linux 的 Windows 子系统 (WSL)。
- macOS 14 Ventura 或更高版本。
- Debian 12、Debian 13、Ubuntu 22.04、Ubuntu 24.04,在 x86-64 和 arm64 架构上。