跳转到主要内容

入门 - 库

简介

Playwright 既可以与 MSTest、NUnit、xUnit 或 xUnit v3 基类结合使用,也可以作为 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.net.cn/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.net.cn/dotnet");
await page.ScreenshotAsync(new()
{
Path = "screenshot.png"
});

现在运行它。

dotnet run

默认情况下,Playwright 以无头(headless)模式运行浏览器。若要查看浏览器界面,请将 Headless 选项设置为 false。您还可以使用 SlowMo 来减慢执行速度。在调试工具章节中了解更多信息。

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

使用断言

当您使用自己的测试框架时,可以通过以下方式利用 Playwright 的 Web 优先断言(web-first assertions)。这些断言会自动重试,直到满足条件,例如元素包含特定文本或达到超时时间。

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.net.cn/dotnet");
await Expect(page.GetByRole(AriaRole.Link, new() { Name = "Get started" })).ToBeVisibleAsync();

为不同平台打包驱动程序

默认情况下,Playwright 仅为 .NET 发布的目标运行时(target runtime)打包驱动程序。如果您想为其他平台打包,可以在项目文件中通过使用 allnone 或者 linuxwinosx 来覆盖此行为。

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

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