跳到主要内容

安装

简介

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.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上运行。这可以通过CLI选项配置。测试以无头模式运行,意味着运行测试时不会打开浏览器UI。测试结果和日志将显示在终端中。

pytest

更新Playwright

要更新到最新版本的Playwright,运行以下命令:

pip install pytest-playwright playwright -U

系统要求

  • Python 3.8或更高版本
  • Windows 10+、Windows Server 2016+或Windows Subsystem for Linux (WSL)
  • macOS 14 Ventura或更高版本
  • Debian 12、Ubuntu 22.04、Ubuntu 24.04,支持x86-64和arm64架构

下一步