1. Introduction to Playwright C# Examples
Modern web applications need reliable testing across different browsers and devices. Manual testing alone can take considerable time, especially when an application has multiple features, forms, and user workflows.
This is where Playwright and C# become useful. Playwright is a browser automation framework that allows QA engineers and developers to automate web applications using readable C# code.
In this Playwright C# examples tutorial, you will learn how to create a project, launch browsers, interact with web elements, validate application behavior, and execute automated tests using NUnit.
The examples are designed for beginners, Selenium testers moving to Playwright, QA Automation Engineers, and SDETs. You will also learn how to organize scripts using the Page Object Model (POM) and troubleshoot common automation problems.
By the end, you will have a practical foundation for building maintainable Playwright test automation projects with C#.
2. What Is Playwright with C#?
Playwright is an open-source browser automation framework developed by Microsoft. It supports Chromium, Firefox, and WebKit browsers.
With the Microsoft.Playwright library, developers can write C# programs to control browsers and test web applications.
Playwright with C# supports:
- Browser launching and navigation.
- Clicking buttons and entering text.
- Working with dropdowns and checkboxes.
- Handling browser contexts and sessions.
- Taking screenshots.
- Validating page content and application behavior.
- Running automated tests through test frameworks such as NUnit.
For example, the following C# code opens a browser and navigates to a website:
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(
new BrowserTypeLaunchOptions
{
Headless = false
});
var page = await browser.NewPageAsync();
await page.GotoAsync(“https://example.com”);
Console.WriteLine(await page.TitleAsync());
Here, Headless = false opens the browser window so you can watch the automation.
3. Benefits and Real-World Use Cases
Playwright provides several features that make it useful for modern web testing.
Benefits
Cross-browser testing: Run the same automation scripts against Chromium, Firefox, and WebKit.
Automatic waiting: Playwright waits for elements to become actionable before performing operations.
Reliable locators: Use methods such as GetByRole(), GetByText(), and GetByLabel() to identify elements.
Browser contexts: Create isolated browser sessions for different users or test scenarios.
Screenshots and debugging: Capture screenshots and inspect failures to understand what went wrong.
Asynchronous execution: Use C# async and await to work with browser operations without blocking unnecessarily.
Real-world use cases
| Use case | Example |
| Login testing | Verify valid and invalid login credentials |
| Form testing | Enter information and submit a registration form |
| Search testing | Search for a product and verify results |
| E-commerce testing | Add products to a cart and verify checkout |
| Regression testing | Recheck important application features after changes |
| Cross-browser testing | Verify application behavior across browser engines |
These use cases are common in QA engineering teams where test automation helps reduce repetitive manual work.
4. Prerequisites and Environment Setup
Before starting the Playwright C# examples, install the following tools:
- .NET SDK: Install a supported .NET SDK from the official Microsoft .NET website.
- Visual Studio or Visual Studio Code: Use an editor to create and manage C# projects.
- PowerShell: Required for running the Playwright browser installation script on Windows.
- Basic C# knowledge: Understand classes, methods, variables, and asynchronous programming.
Verify that .NET is installed:
dotnet –version
If the command displays a version number, the .NET SDK is available.
5. Creating Your First Playwright C# Project
Follow these steps to create a Playwright project.
Step 1: Create a .NET console application
Open a terminal and execute:
dotnet new console -n PlaywrightCSharpExamples
cd PlaywrightCSharpExamples
This creates a console application.
Step 2: Install Microsoft.Playwright
Run:
dotnet add package Microsoft.Playwright
This package provides the Playwright API for C#.
Step 3: Build the project
dotnet build
Building the project generates the Playwright browser installation script in the output directory.
Step 4: Install Playwright browsers
For Windows PowerShell:
pwsh bin/Debug/net8.0/playwright.ps1 install
For macOS or Linux:
pwsh bin/Debug/net8.0/playwright.sh install
Replace net8.0 with your project’s actual target framework if it is different.
To install browser dependencies on supported Linux environments, use:
pwsh bin/Debug/net8.0/playwright.sh install –with-deps
Step 5: Run your project
dotnet run
Your environment is now ready for browser automation.
6. Practical Playwright C# Code Examples
Let’s explore useful Playwright C# examples that you can apply to real web applications.
Example 1: Launch a browser and navigate to a website
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(
new BrowserTypeLaunchOptions
{
Headless = false
});
var page = await browser.NewPageAsync();
await page.GotoAsync(“https://example.com”);
Console.WriteLine(“Page title: ” + await page.TitleAsync());
Console.WriteLine(“Current URL: ” + page.Url);
Explanation:
- Playwright.CreateAsync() initializes Playwright.
- Chromium.LaunchAsync() launches Chromium.
- NewPageAsync() creates a new browser page.
- GotoAsync() navigates to the requested URL.
- TitleAsync() retrieves the page title.
Example 2: Locate elements and click a button
Playwright provides different locator methods. Prefer accessible locators such as role-based locators whenever possible.
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://example.com”);
var moreInfoLink = page.GetByRole(
AriaRole.Link,
new PageGetByRoleOptions { Name = “More information…” }
);
await moreInfoLink.ClickAsync();
GetByRole() identifies an element using its accessible role and name. This often produces more reliable tests than depending on complicated CSS selectors.
Example 3: Fill a login form
The following example demonstrates how to enter login details.
await page.GotoAsync(“https://your-application.com/login”);
await page.GetByLabel(“Email”).FillAsync(“test@example.com”);
await page.GetByLabel(“Password”).FillAsync(“TestPassword123”);
await page.GetByRole(
AriaRole.Button,
new PageGetByRoleOptions { Name = “Login” }
).ClickAsync();
Replace the URL and labels with the actual values from your application.
For production testing, store credentials securely rather than hardcoding passwords in test files.
Example 4: Handle a dropdown
Playwright supports selecting options from standard HTML select elements.
await page.GotoAsync(“https://your-application.com/register”);
await page.Locator(“#country”).SelectOptionAsync(
new SelectOptionValue { Label = “India” }
);
You can also select an option using its value:
await page.Locator(“#country”).SelectOptionAsync(“IN”);
Use SelectOptionAsync() for HTML <select> elements. Custom dropdown components may require clicking the dropdown and selecting an option using its locator.
Example 5: Validate a result using assertions
Playwright provides web-first assertions through Expect(). These assertions automatically retry until the expected condition is satisfied or the timeout expires.
using Microsoft.Playwright;
using static Microsoft.Playwright.Assertions;
await page.GotoAsync(“https://example.com”);
await Expect(page).ToHaveTitleAsync(“Example Domain”);
await Expect(
page.GetByRole(AriaRole.Heading, new PageGetByRoleOptions
{
Name = “Example Domain”
})
).ToBeVisibleAsync();
These assertions are more reliable than immediately checking an element’s state because they allow time for the page to update.
Example 6: Capture a screenshot
Screenshots help QA engineers investigate failures and understand unexpected application behavior.
await page.ScreenshotAsync(new PageScreenshotOptions
{
Path = “screenshots/homepage.png”,
FullPage = true
});
Create the screenshots directory before capturing the screenshot. You can also capture a screenshot after a failed test in your NUnit teardown method.
Example 7: Create an isolated browser context
Browser contexts allow tests to use separate sessions without sharing cookies or local storage.
var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();
await page.GotoAsync(“https://example.com”);
Console.WriteLine(await page.TitleAsync());
await context.CloseAsync();
This is especially useful when testing multiple user accounts or authentication scenarios.
7. Using NUnit for Test Execution
NUnit is a popular unit-testing framework for .NET. It can also be used as a test runner for Playwright browser automation.
Install the required packages:
dotnet add package Microsoft.Playwright
dotnet add package NUnit
dotnet add package NUnit3TestAdapter
dotnet add package Microsoft.NET.Test.Sdk
Practical NUnit example with setup and teardown
Create a file named LoginTests.cs.
using Microsoft.Playwright;
using NUnit.Framework;
using static Microsoft.Playwright.Assertions;
[TestFixture]
public class LoginTests
{
private IPlaywright _playwright = null!;
private IBrowser _browser = null!;
private IBrowserContext _context = null!;
private IPage _page = null!;
[SetUp]
public async Task SetUp()
{
_playwright = await Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync(
new BrowserTypeLaunchOptions
{
Headless = true
});
_context = await _browser.NewContextAsync();
_page = await _context.NewPageAsync();
}
[Test]
public async Task VerifyHomepageTitle()
{
await _page.GotoAsync(“https://example.com”);
await Expect(_page).ToHaveTitleAsync(“Example Domain”);
}
[TearDown]
public async Task TearDown()
{
if (_context != null)
await _context.CloseAsync();
if (_browser != null)
await _browser.CloseAsync();
_playwright?.Dispose();
}
}
How it works:
- [TestFixture] identifies the NUnit test class.
- [SetUp] runs before each test and initializes Playwright.
- [Test] identifies the test method.
- Expect() checks the expected page title.
- [TearDown] closes the browser context, browser, and Playwright instance.
Execute NUnit tests
Run:
dotnet test
NUnit discovers and executes the test methods.
For more complex projects, you can add multiple test classes, test data, and configuration files to organize your automation suite.
8. Page Object Model Example
The Page Object Model is a design pattern that separates page-specific locators and actions from test logic.
It improves readability, reusability, and maintenance.
Recommended project structure
PlaywrightCSharpExamples/
│
├── Pages/
│ └── LoginPage.cs
│
├── Tests/
│ └── LoginTests.cs
│
├── screenshots/
│
└── PlaywrightCSharpExamples.csproj
Step 1: Create LoginPage.cs
using Microsoft.Playwright;
public class LoginPage
{
private readonly IPage _page;
public LoginPage(IPage page)
{
_page = page;
}
private ILocator Email =>
_page.GetByLabel(“Email”);
private ILocator Password =>
_page.GetByLabel(“Password”);
private ILocator LoginButton =>
_page.GetByRole(
AriaRole.Button,
new PageGetByRoleOptions { Name = “Login” }
);
public async Task OpenAsync()
{
await _page.GotoAsync(
“https://your-application.com/login”
);
}
public async Task LoginAsync(string email, string password)
{
await Email.FillAsync(email);
await Password.FillAsync(password);
await LoginButton.ClickAsync();
}
}
Step 2: Create LoginTests.cs
using NUnit.Framework;
using static Microsoft.Playwright.Assertions;
[TestFixture]
public class LoginTests : PlaywrightTestBase
{
[Test]
public async Task VerifyLoginPage()
{
var loginPage = new LoginPage(Page);
await loginPage.OpenAsync();
await loginPage.LoginAsync(
“test@example.com”,
“TestPassword123”
);
await Expect(Page).ToHaveURLAsync(
“https://your-application.com/dashboard”
);
}
}
For this example, PlaywrightTestBase is a shared test base class that manages browser and page initialization. It should expose a Page property and implement setup and teardown, similar to the NUnit example in the previous section.
The application URL, labels, credentials, and expected dashboard URL must match your test environment.
Why use POM?
- Locators are maintained in one place.
- Test methods remain short and readable.
- Reusable page methods reduce duplicate code.
- Changes to a page can be handled without rewriting every test.
For larger projects, explore the TechSarvam pillar article Playwright Framework Design to understand how to combine POM, configuration, test data, reporting, and reusable utilities.
9. Common Errors and Troubleshooting
Beginners may face a few common problems while implementing Playwright C# examples.
| Error or problem | Possible solution |
| Browser executable not found | Run the Playwright browser installation script |
| Element not found | Verify the locator and check whether the element exists |
| Timeout exceeded | Check page loading, locator accuracy, and expected state |
| Test fails intermittently | Use web-first assertions instead of fixed delays |
| Browser does not open | Set Headless = false and check the browser installation |
| Screenshot fails | Ensure the destination directory exists |
| Package not found | Check the package name and restore NuGet dependencies |
Debugging tips
Use headed mode to observe browser actions:
Headless = false
Use a longer timeout when the application genuinely needs additional time:
await page.GetByRole(AriaRole.Button,
new PageGetByRoleOptions { Name = “Submit” }
).ClickAsync(new LocatorClickOptions
{
Timeout = 10000
});
Avoid adding fixed waits such as WaitForTimeoutAsync() as a routine solution. First investigate why the application or locator is not reaching the expected state.
10. Best Practices for Playwright C# Automation
Follow these practices to build reliable automation scripts:
- Use meaningful locators: Prefer GetByRole(), GetByLabel(), and GetByTestId() where appropriate.
- Use async and await correctly: Await Playwright operations to ensure actions complete in the expected order.
- Use browser contexts: Isolate test sessions to prevent cookies and storage from affecting other tests.
- Follow Page Object Model: Keep locators and page actions separate from test logic.
- Avoid hardcoded waits: Use Playwright’s automatic waiting and web-first assertions.
- Keep credentials secure: Use environment variables or a secure secret store.
- Capture screenshots: Save useful evidence when tests fail.
- Write independent tests: Each test should be able to run without depending on another test.
- Use meaningful test names: Describe the expected behavior clearly.
- Run cross-browser tests: Test important workflows against Chromium, Firefox, and WebKit.
These practices help teams create maintainable test automation that can run locally and in continuous integration pipelines.
11. Interview Questions and Career Guidance
If you are preparing for QA Automation Engineer or SDET interviews, understand the following Playwright C# topics.
1. What is Playwright?
Playwright is a browser automation framework that supports Chromium, Firefox, and WebKit.
2. What is Microsoft.Playwright?
It is the .NET library used to automate browsers using C#.
3. What is the difference between a browser and a browser context?
A browser is the browser instance, while a browser context represents an isolated session with its own cookies and storage.
4. What is a locator in Playwright?
A locator identifies an element on a web page and provides methods to interact with it.
5. What is the purpose of async and await?
They help manage asynchronous operations. Playwright APIs commonly return Task values, which should be awaited to ensure operations complete correctly.
6. What is the Page Object Model?
POM is a design pattern that separates page locators and actions from test methods.
7. How do you validate a page title?
Use a web-first assertion:
await Expect(page).ToHaveTitleAsync(“Example Domain”);
8. How do you take a screenshot?
Use ScreenshotAsync() with a PageScreenshotOptions object.
