跳到主内容

安装

简介

Playwright 专为满足端到端测试的需求而创建。Playwright 支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上进行测试,可在本地或 CI 上运行,支持无头或有头模式,并具备原生移动设备模拟功能。

Playwright 库可用作通用的浏览器自动化工具,提供强大的 API 集来自动化 Web 应用程序,同时支持同步和异步 Python。

本简介描述了 Playwright Pytest 插件,这是编写端到端测试的推荐方式。

您将了解

安装 Playwright Pytest

Playwright 推荐使用官方的 Playwright Pytest 插件来编写端到端测试。它提供上下文隔离,并开箱即用地支持在多种浏览器配置上运行测试。

通过安装 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.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、Ubuntu 22.04、Ubuntu 24.04,支持 x86-64 和 arm64 架构。

下一步