To use Playwright, you need to install the NuGet package and the browsers. The documentation recommends the following commands:
Shell
# Create project
dotnet new console -n PlaywrightDemo
cd PlaywrightDemo
# Install dependencies, build project and download necessary browsers.
dotnet add package Microsoft.Playwright
dotnet build
dotnet tool install --global Microsoft.Playwright.CLI
playwright install
This works fine on the developer machine. However, playwright install must run in the project directory because it requires a csproj file. It also requires the .NET SDK, since it is a dotnet tool. This is a showstopper when distributing an application, as you cannot expect end users to have the .NET SDK installed.
Instead of relying on playwright install, you can use an alternative approach. The playwright install command is just a small utility that calls Microsoft.Playwright.Program.Run. This method lives in Microsoft.Playwright.dll, which is included in the Microsoft.Playwright NuGet package. This means you can call it directly from your application code, with no CLI required.
C#
using Microsoft.Playwright;
Console.WriteLine("Installing browsers");
// The following line installs the default browsers. If you only need a subset of browsers,
// you can specify the list of browsers you want to install among: chromium, chrome,
// chrome-beta, msedge, msedge-beta, msedge-dev, firefox, and webkit.
// var exitCode = Microsoft.Playwright.Program.Main(new[] { "install", "webkit", "chrome" });
// If you need to install dependencies, you can add "--with-deps"
var exitCode = Microsoft.Playwright.Program.Main(new[] { "install" });
if (exitCode != 0)
{
Console.WriteLine("Failed to install browsers");
Environment.Exit(exitCode);
}
Console.WriteLine("Browsers installed");
// Using playwright to launch a browser
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
await using var browserContext = await browser.NewContextAsync();
var page = await browserContext.NewPageAsync();
await page.GotoAsync("https://www.meziantou.net");
Console.WriteLine(await page.InnerTextAsync("h1"));
Do you have a question or a suggestion about this post? Contact me!