Skip to main content

開始使用 - 函式庫

簡介

Playwright 可以與 MSTestNUnit 一起使用,或作為 Playwright 函式庫(本指南)。如果您正在開發利用 Playwright 功能的應用程式或將 Playwright 與其他測試執行器一起使用,請繼續閱讀。

使用方式

建立一個主控台專案並新增 Playwright 相依套件。

# Create project
dotnet new console -n PlaywrightDemo
cd PlaywrightDemo

# Add project dependency
dotnet add package Microsoft.Playwright
# Build the project
dotnet build
# Install required browsers - replace netX with actual output folder name, e.g. net8.0.
pwsh bin/Debug/netX/playwright.ps1 install

# If the pwsh command does not work (throws TypeNotFound), make sure to use an up-to-date version of PowerShell.
dotnet tool update --global PowerShell

建立一個 Program.cs,將導航到 https://playwright.dev/dotnet 並在 Chromium 中截圖。

using Microsoft.Playwright;

using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://playwright.dev/dotnet");
await page.ScreenshotAsync(new()
{
Path = "screenshot.png"
});
dotnet run

預設情況下,Playwright 以無頭模式執行瀏覽器。要查看瀏覽器 UI,啟動瀏覽器時傳遞 Headless = false 旗標。您也可以使用 slowMo 來減慢執行速度。了解更多在偵錯工具部分

await using var browser = await playwright.Firefox.LaunchAsync(new()
{
Headless = false,
SlowMo = 50,
});

使用 Assertions

你可以執行以下操作來利用 Playwright 的 web-first 斷言,當你使用自己的測試框架時。這些將自動重試直到條件滿足,例如一個元素有特定的文本或達到超時時間:

using Microsoft.Playwright;
using static Microsoft.Playwright.Assertions;

// Change the default 5 seconds timeout if you'd like.
SetDefaultExpectTimeout(10_000);

using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://playwright.dev/dotnet");
await Expect(page.GetByRole(AriaRole.Link, new() { Name = "Get started" })).ToBeVisibleAsync();

為不同平台捆綁驅動程式

Playwright 預設僅包含 .NET 發佈目標執行階段的驅動程式。如果您想要為其他平台包含,您可以在您的專案檔中使用 allnonelinuxwinosx 來覆蓋此行為。

<PropertyGroup>
<PlaywrightPlatform>all</PlaywrightPlatform>
</PropertyGroup>

或者:

<PropertyGroup>
<PlaywrightPlatform>osx;linux</PlaywrightPlatform>
</PropertyGroup>