安裝
簡介
Playwright 的創建 বিশেষভাবে 符合端對端測試的需求。Playwright 支援所有現代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上進行測試,本地端或 CI 皆可,無頭或有頭模式皆可,並具備原生行動裝置模擬功能。
Playwright 程式庫可以作為通用的瀏覽器自動化工具使用,為同步和非同步 Python 提供一組強大的 API,以自動化 Web 應用程式。
本簡介描述了 Playwright Pytest 外掛程式,這是編寫端對端測試的建議方式。
您將學到
安裝 Playwright Pytest
Playwright 建議使用官方的 Playwright Pytest 外掛程式來編寫端對端測試。它提供了 context isolation(上下文隔離),開箱即用即可在多個瀏覽器配置上運行。
開始使用,先安裝 Playwright 並執行範例測試以查看其運作方式。
- PyPI
- Anaconda
安裝 Pytest 外掛程式
pip install pytest-playwright
安裝 Pytest 外掛程式
conda config --add channels conda-forge
conda config --add channels microsoft
conda 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.org.tw/")
# 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.org.tw/")
# 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 13 Ventura 或更高版本。
- Debian 12、Ubuntu 22.04、Ubuntu 24.04,在 x86-64 和 arm64 架構上。