安裝
簡介
Playwright 的創建是為了滿足端對端測試的需求。Playwright 支援所有現代渲染引擎,包括 Chromium、WebKit 和 Firefox。在 Windows、Linux 和 macOS 上進行測試,本地或在 CI 上,無頭或有頭模式,並具有原生行動裝置模擬功能。
Playwright 函式庫可以用作通用的瀏覽器自動化工具,提供一組強大的 API 來自動化 Web 應用程式,適用於同步和非同步 Python。
本簡介描述了 Playwright Pytest 外掛程式,這是編寫端對端測試的建議方式。
您將學習
安裝 Playwright Pytest
Playwright 建議使用官方的 Playwright Pytest 外掛程式 來編寫端對端測試。它提供了上下文隔離,並開箱即用地在多個瀏覽器配置上運行。
開始使用,先安裝 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 架構上。