Skip to main content

安装

Playwright 是专门为满足端到端测试需求而创建的。Playwright 支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。支持在 Windows、Linux 和 macOS 上进行测试,无论是在本地还是 CI 环境,无头模式还是有头模式,以及原生移动模拟。

Playwright 推荐使用官方的 Playwright Pytest 插件 来编写端到端测试。它提供上下文隔离,开箱即用地在多个浏览器配置上运行。或者,您可以使用 手动编写测试基础设施,并使用您喜欢的测试运行器。Pytest 插件使用 Playwright 的同步版本,也可以通过库访问异步版本。

安装 Playwright 并运行示例测试以开始使用。

安装 Pytest 插件

pip install pytest-playwright

安装所需的浏览器:

playwright install

添加示例测试

在当前工作目录或子目录中创建一个 test_my_application.py 文件,代码如下:

import re
from playwright.sync_api import Page, expect


def test_homepage_has_Playwright_in_title_and_get_started_link_linking_to_the_intro_page(page: Page):
page.goto("https://playwright.dev/")

# Expect a title "to contain" a substring.
expect(page).to_have_title(re.compile("Playwright"))

# create a locator
get_started = page.locator("text=Get Started")

# Expect an attribute "to be strictly equal" to the value.
expect(get_started).to_have_attribute("href", "/docs/intro")

# Click the get started link.
get_started.click()

# Expects the URL to contain intro.
expect(page).to_have_url(re.compile(".*intro"))

运行示例测试

默认情况下,测试将在 chromium 上运行。这可以通过 CLI 选项进行配置。测试以无头模式运行,这意味着运行测试时不会打开浏览器 UI。测试结果和测试日志将显示在终端中。

pytest

接下来