Playwright 入门介绍 , Playwright 使用指南 请参考另一篇博客

此博客为Playwright官网译文 希望让读者可以快速了解 Playwriht 可以用来做什么,怎么用。有些专业名词可能翻译不准确哈


文章目录

  • 1.入门
  • 1.1 Installation 安装
  • 1.1.1 Add Example Test 添加示例测试
  • 1.1.2 Running the Example Test 运行示例测试
  • 1.2 Writing Tests 编写测试
  • 1.2.1 Assertions 断言
  • 1.2.2 Locators 定位器
  • 1.2.3 Test Isolation 测试隔离
  • 1.2.4 Using Test Hooks 使用测试钩子
  • 1.3 Running Tests 运行测试
  • 1.3.1 Running Tests 运行测试
  • 1.4 Test Generator 测试生成器
  • 1.4.1 Running Codegen 运行
  • 1.5 Trace Viewer 跟踪查看器
  • 1.5.1 Recording a trace 记录轨迹
  • 1.5.2 Opening the trace 打开跟踪
  • 1.5.3 Viewing the trace 查看轨迹
  • 1.6 Pytest 插件参考
  • 1.6 Examples 例子
  • 1.7 配合unittest.TestCase使用


1.入门

1.1 Installation 安装

Playwright 是专门为满足端到端测试的需求而创建的。Playwright 支持所有现代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上进行测试,在本地或在 CI 上进行测试,无头或使用本机移动仿真。

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

开始安装 Playwright 并运行示例测试以查看它的运行情况。

安装Pytest 插件:

pip install pytest-playwright

安装所需的浏览器:

playwright install

1.1.1 Add Example Test 添加示例测试

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"))

1.1.2 Running the Example Test 运行示例测试

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

pytest

1.2 Writing Tests 编写测试

Playwright断言是专门为动态网络创建的。检查会自动重试,直到满足必要的条件。Playwright 带有内置的auto-wait自动等待功能,这意味着它会在执行操作之前等待元素可操作。Playwright 提供了一个expect函数来编写断言。

查看下面的示例测试,了解如何使用 Web 优先断言、定位器和选择器编写测试。

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"))

1.2.1 Assertions 断言

Playwright 提供了expect等待满足预期条件的功能。

import re
from playwright.sync_api import expect

expect(page).to_have_title(re.compile("Playwright"))

1.2.2 Locators 定位器

定位器 是Playwright 自动等待和重试能力的核心部分。定位器代表了一种随时在页面上查找元素的方法,并用于对诸如等元素执行操作。可以使用page.locator(selector, **kwargs)方法.click .fill创建自定义定位器。

from playwright.sync_api import expect

get_started = page.locator("text=Get Started")

expect(get_started).to_have_attribute("href", "/docs/installation")
get_started.click()

选择器

from playwright.sync_api import expect

expect(page.locator("text=Installation")).to_be_visible()

1.2.3 Test Isolation 测试隔离

Playwright Pytest 插件基于测试夹具的概念,例如built in page fixture内置的页面夹具,它被传递到您的测试中。由于浏览器上下文,页面在测试之间是隔离的,这相当于一个全新的浏览器配置文件,其中每个测试都会获得一个全新的环境,即使在单个浏览器中运行多个测试也是如此。

from playwright.sync_api import Page

def test_basic_test(page: Page):
  # ...

1.2.4 Using Test Hooks 使用测试钩子

您可以使用各种fixtures夹具在测试之前或之后执行代码,并在它们之间共享对象。一个function作用域的夹具,例如具有自动使用的行为就像一个 beforeEach/afterEach。具有自动使用的module作用域夹具的行为类似于在所有测试之前和之后运行的 beforeAll/afterAll。

import pytest
from playwright.sync_api import Page


@pytest.fixture(scope="function", autouse=True)
def before_each_after_each(page: Page):
    print("beforeEach")
    # Go to the starting url before each test.
    page.goto("https://playwright.dev/")
    yield
    print("afterEach")

def test_main_navigation(page: Page):
    # Assertions use the expect API.
    expect(page).to_have_url("https://playwright.dev/")

1.3 Running Tests 运行测试

您可以运行单个测试、一组测试或所有测试。测试可以在一个浏览器或多个浏览器上运行。默认情况下,测试以无头方式运行,这意味着在运行测试时不会打开浏览器窗口,并且会在终端中看到结果。如果您愿意,可以使用该--headed标志在 headed 模式下运行测试。

  • 在 Chromium 上运行测试
pytest
  • 运行单个测试文件
pytest test_login.py
  • 运行一组测试文件
pytest tests/todo-page/ tests/landing-page/
  • 使用函数名运行测试
pytest -k "test_add_a_todo_item"
  • 以 Headed 模式运行测试
pytest --headed test_login.py
  • 在特定浏览器上运行测试
pytest test_login.py --browser webkit
  • 在多个浏览器上运行测试
pytest test_login.py --browser webkit --browser firefox
  • 并行运行测试
pytest --numprocesses auto

(这假定pytest-xdist已安装。有关更多信息,请参见官方文档。)

1.3.1 Running Tests 运行测试

由于 Playwright 在 Python 中运行,您可以使用您选择的调试器进行调试,例如 Visual Studio Code 中的[Python 扩展]。Playwright 附带了 Playwright Inspector,它允许您单步执行 Playwright API 调用,查看他们的调试日志并探索选择器。

Bash

PWDEBUG=1 pytest -s

PowerShell

$env:PWDEBUG=1
pytest -s

Batch

set PWDEBUG=1
pytest -s

Playwright 入门介绍和使用指南_Playwright

1.4 Test Generator 测试生成器

Playwright 具有开箱即用生成测试的能力,是快速开始测试的好方法。它将打开两个窗口,一个是浏览器窗口,您可以在其中与您希望测试的网站进行交互,另一个是 Playwright Inspector 窗口,您可以在其中记录您的测试、复制测试、清除测试以及更改测试的语言。

1.4.1 Running Codegen 运行

playwright codegen playwright.dev

在浏览器中运行codegen和执行操作。Playwright 将为用户交互生成代码。Codegen将尝试生成有弹性的基于文本的选择器。

Playwright 入门介绍和使用指南_Playwright_02

当您完成与页面的交互后,按下录制按钮停止录制并使用复制按钮将生成的代码复制到您的编辑器。

Playwright 入门介绍和使用指南_Playwright_03

使用清除按钮清除代码以重新开始录制。完成后关闭 Playwright 检查器窗口或停止终端命令。

要了解有关生成测试的更多信息,请查看官网详细指南。

1.5 Trace Viewer 跟踪查看器

Playwright Trace Viewer 是一个 GUI 工具,可让您探索记录的 Playwright 测试跟踪,这意味着您可以在测试的每个动作中前后移动,并直观地查看每个动作期间发生的情况。

你将学习

  • 如何记录轨迹
  • 如何打开 HTML 报告
  • 如何打开跟踪查看器

1.5.1 Recording a trace 记录轨迹

可以使用browser_context.tracingAPI 记录跟踪,如下所示:

Sync 同步

browser = chromium.launch()
context = browser.new_context()

# Start tracing before creating / navigating a page.
context.tracing.start(screenshots=True, snapshots=True, sources=True)

page.goto("https://playwright.dev")

# Stop tracing and export it into a zip archive.
context.tracing.stop(path = "trace.zip")

Async 异步

browser = await chromium.launch()
context = await browser.new_context()

# Start tracing before creating / navigating a page.
await context.tracing.start(screenshots=True, snapshots=True, sources=True)

await page.goto("https://playwright.dev")

# Stop tracing and export it into a zip archive.
await context.tracing.stop(path = "trace.zip")

这将记录跟踪并将其放入名为trace.zip.

1.5.2 Opening the trace 打开跟踪

您可以使用 Playwright CLI 或在浏览器中打开保存的跟踪trace.playwright.dev

playwright show-trace trace.zip

1.5.3 Viewing the trace 查看轨迹

通过单击每个操作或使用时间线悬停来查看测试的跟踪,并查看操作之前和之后的页面状态。在测试的每个步骤中检查日志、源和网络。跟踪查看器会创建一个 DOM 快照,以便您可以与其完全交互、打开开发工具等。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t0Msq8XP-1663298007245)(Playwright/image-20220916093431785.png)]

要了解更多信息,请查看官方文档。

1.6 Pytest 插件参考

Playwright 提供了一个Pytest插件来编写端到端测试。要开始使用它,请参阅本文入门指南。

Usage用途

要运行测试,请使用Pytest CLI。

pytest --browser webkit --headed

如果要自动添加 CLI 参数而不指定它们,可以使用[pytest.ini]文件:

CLI arguments CLI参数

  • --headed:在有头模式下运行测试(默认:无头)。
  • --browser:在不同的浏览器中运行测试chromiumfirefoxwebkit。可以多次指定(默认:所有浏览器)。
  • --browser-channel 要使用的[浏览器频道
  • --slowmo以慢动作运行测试。
  • --device 要模拟的设备
  • --output测试产生的工件目录(默认值:)test-results
  • --tracing是否为每个测试记录跟踪。on, off, 或retain-on-failure(默认值:off)。
  • --video是否为每次测试录制视频。on, off, 或retain-on-failure(默认值:off)。
  • --screenshot每次测试后是否自动截屏。on, off, 或only-on-failure(默认值:off)。

Fixtures 夹具

此插件为 pytest配置特定于 Playwright 的装置。要使用这些夹具,请使用夹具名称作为测试函数的参数。

def test_my_app_is_working(fixture_name):
    # Test using fixture_name
    # ...

Function scope功能范围:这些夹具在测试功能中请求时创建,并在测试结束时销毁。

  • context:用于测试的新浏览器上下文。
  • page:用于测试的新浏览器页面。

Session scope 会话范围:这些夹具在测试函数中请求时创建,并在所有测试结束时销毁。

  • playwright:Pyaywright实例。
  • browser_type:当前浏览器的BrowserType实例。
  • browser: Playwright 启动的浏览器实例。
  • browser_name:浏览器名称作为字符串。
  • browser_channel: 浏览器频道作为字符串。
  • is_chromium, is_webkit, is_firefox: 相应浏览器类型的布尔值。

Customizing fixture options自定义夹具选项:对于browsercontext夹具,使用以下夹具来定义自定义启动选项。

  • browser_type_launch_args:覆盖browser_type.launch(**kwargs)的启动参数。它应该返回一个字典。
  • browser_context_args: 覆盖browser.new_context(**kwargs)的选项。它应该返回一个字典。

**Parallelism: Running Multiple Tests at Once 并行性:**一次运行多个测试

pytest-xdist如果您的测试在具有大量 CPU 的机器上运行,您可以通过一次运行多个测试来加快测试套件的整体执行时间:

# install dependency
pip install pytest-xdist
# use the --numprocesses flag
pytest --numprocesses auto

根据测试的硬件和性质,您可以设置为从机器上的 CPU 数量numprocesses到任意位置。2如果设置得太高,您可能会注意到意外行为。

有关选项的一般信息,请参阅pytest

1.6 Examples 例子

**Configure Mypy typings for auto-completion **配置Mypy类型自动完成

# test_my_application.py
from playwright.sync_api import Page

def test_visit_admin_dashboard(page: Page):
    page.goto("/admin")
    # ...

**Configure slow mo **配置缓存

使用参数以慢速运行测试--slowmo

pytest --slowmo 100

Skip test by browser 通过浏览器跳过测试

# test_my_application.py
import pytest

@pytest.mark.skip_browser("firefox")
def test_visit_example(page):
    page.goto("https://example.com")
    # ...

Run on a specific browser 在特定浏览器上运行

# conftest.py
import pytest

@pytest.mark.only_browser("chromium")
def test_visit_example(page):
    page.goto("https://example.com")
    # ...

Run with a custom browser channel like Google Chrome or Microsoft Edge使用自定义浏览器通道(如 Google Chrome 或 Microsoft Edge)

pytest --browser-channel chrome
# test_my_application.py
def test_example(page):
    page.goto("https://example.com")

Configure base-url配置base- url

使用参数启动 Pytest base-url。该pytest-base-ur插件用于允许您从配置、CLI arg 或作为夹具设置基本 url。

pytest --base-url http://localhost:8080
# test_my_application.py
def test_visit_example(page):
    page.goto("/admin")
    # -> Will result in http://localhost:8080/admin

Ignore HTTPS errors 忽略 HTTPS错误

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "ignore_https_errors": True
    }

Use custom viewport size 使用自定窗口大小

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    return {
        **browser_context_args,
        "viewport": {
            "width": 1920,
            "height": 1080,
        }
    }

Device emulation 设备模拟

# conftest.py
import pytest

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright):
    iphone_11 = playwright.devices['iPhone 11 Pro']
    return {
        **browser_context_args,
        **iphone_11,
    }

或通过 CLI--device="iPhone 11 Pro"

Persistent context持久的

# conftest.py
import pytest
from playwright.sync_api import BrowserType
from typing import Dict

@pytest.fixture(scope="session")
def context(
    browser_type: BrowserType,
    browser_type_launch_args: Dict,
    browser_context_args: Dict
):
    context = browser_type.launch_persistent_context("./foobar", **{
        **browser_type_launch_args,
        **browser_context_args,
        "locale": "de-DE",
    })
    yield context
    context.close()

使用该测试时,测试中的所有页面都是从持久上下文创建的。

1.7 配合unittest.TestCase使用

请参阅以下示例以将其与unittest.TestCase. 这有一个限制,即只能指定一个浏览器,并且在指定多个浏览器时不会生成多个浏览器的矩阵。

import pytest
import unittest

from playwright.sync_api import Page


class MyTest(unittest.TestCase):
    @pytest.fixture(autouse=True)
    def setup(self, page: Page):
        self.page = page

    def test_foobar(self):
        self.page.goto("https://microsoft.com")
        self.page.locator("#foobar").click()
        assert self.page.evaluate("1 + 1") == 2

Debugging 调试

使用breakpoint()测试代码中的语句暂停执行并获取pdb REPL。

def test_bing_is_working(page):
    page.goto("https://bing.com")
    breakpoint()
    # ...

Deploy to CI 部署到CI

请参阅官方文档将您的测试部署到 CI/CD。