Skip to main content

安裝

簡介

Playwright 專為滿足端對端測試需求而建立。Playwright 支援所有現代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上測試,無論是本機或在 CI 上,支援無頭或有頭模式,並提供原生行動裝置模擬。

Playwright 程式庫可作為通用瀏覽器自動化工具使用,為同步和非同步 Python 提供強大的 API 集來自動化 Web 應用程式。

本簡介描述 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(page).to_have_title(re.compile("Playwright"))

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

# 點擊開始使用連結。
page.get_by_role("link", name="Get started").click()

# 期望頁面有名為 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 11+、Windows Server 2019+ 或適用於 Linux 的 Windows 子系統(WSL)。
  • macOS 14 Ventura 或更新版本。
  • Debian 12、Debian 13、Ubuntu 22.04、Ubuntu 24.04,在 x86-64 和 arm64 架構上。

下一步