Skip to main content

入門 - 程式庫

簡介

Playwright 可以與 MSTest、NUnit、xUnit 或 xUnit v3 基礎類別一起使用,或作為 Playwright Library(本指南)使用。如果您正在開發利用 Playwright 功能的應用程式或將 Playwright 與另一個測試執行器一起使用,請繼續閱讀。

使用方式

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

# 建立專案
dotnet new console -n PlaywrightDemo
cd PlaywrightDemo

# 新增專案相依性
dotnet add package Microsoft.Playwright
# 建置專案
dotnet build
# 安裝所需的瀏覽器 - 將 netX 替換為實際的輸出資料夾名稱,例如 net8.0。
pwsh bin/Debug/netX/playwright.ps1 install

# 如果 pwsh 命令無法工作(拋出 TypeNotFound),請確保使用最新版本的 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

By default, Playwright runs the browsers in headless mode. To see the browser UI, set Headless option to false. You can also use SlowMo to slow down execution. Learn more in the debugging tools section.

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

Using Assertions

You can do the following to leverage Playwright's web-first assertions when you are using your own test framework. These will automatically retry until the condition is met, e.g. an element has a certain text or the timeout is reached:

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>

or:

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