跳到主要内容

安装

简介

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 13 Ventura 或更高版本。
  • Debian 12、Ubuntu 22.04、Ubuntu 24.04,在 x86-64 和 arm64 架构上。

下一步