Best Playwright-dotnet code snippet using Microsoft.Playwright.Playwright
TestRunner.cs
Source: TestRunner.cs
...7using System.Runtime.InteropServices;8using System.Threading;9using System.Threading.Tasks;10#if INSTALLPLAYWRIGHT11using PlaywrightSharp;12#endif13namespace RunTests14{15 public class TestRunner16 {17 public TestRunner(RunTestsOptions options)18 {19 Options = options;20 EnvironmentVariables = new Dictionary<string, string>();21 }22 public RunTestsOptions Options { get; set; }23 public Dictionary<string, string> EnvironmentVariables { get; set; }24 public bool SetupEnvironment()25 {26 try27 {28 EnvironmentVariables.Add("DOTNET_CLI_HOME", Options.HELIX_WORKITEM_ROOT);29 EnvironmentVariables.Add("PATH", Options.Path);30 EnvironmentVariables.Add("helix", Options.HelixQueue);31 Console.WriteLine($"Current Directory: {Options.HELIX_WORKITEM_ROOT}");32 var helixDir = Options.HELIX_WORKITEM_ROOT;33 Console.WriteLine($"Setting HELIX_DIR: {helixDir}");34 EnvironmentVariables.Add("HELIX_DIR", helixDir);35 EnvironmentVariables.Add("NUGET_FALLBACK_PACKAGES", helixDir);36 var nugetRestore = Path.Combine(helixDir, "nugetRestore");37 EnvironmentVariables.Add("NUGET_RESTORE", nugetRestore);38 var dotnetEFFullPath = Path.Combine(nugetRestore, helixDir, "dotnet-ef.exe");39 Console.WriteLine($"Set DotNetEfFullPath: {dotnetEFFullPath}");40 EnvironmentVariables.Add("DotNetEfFullPath", dotnetEFFullPath);41 var appRuntimePath = $"{Options.DotnetRoot}/shared/Microsoft.AspNetCore.App/{Options.RuntimeVersion}";42 Console.WriteLine($"Set ASPNET_RUNTIME_PATH: {appRuntimePath}");43 EnvironmentVariables.Add("ASPNET_RUNTIME_PATH", appRuntimePath);44 var dumpPath = Environment.GetEnvironmentVariable("HELIX_DUMP_FOLDER");45 Console.WriteLine($"Set VSTEST_DUMP_PATH: {dumpPath}");46 EnvironmentVariables.Add("VSTEST_DUMP_PATH", dumpPath);47#if INSTALLPLAYWRIGHT48 // Playwright will download and look for browsers to this directory49 var playwrightBrowsers = Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH");50 Console.WriteLine($"Setting PLAYWRIGHT_BROWSERS_PATH: {playwrightBrowsers}");51 EnvironmentVariables.Add("PLAYWRIGHT_BROWSERS_PATH", playwrightBrowsers);52 var playrightDriver = Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_PATH");53 Console.WriteLine($"Setting PLAYWRIGHT_DRIVER_PATH: {playrightDriver}");54 EnvironmentVariables.Add("PLAYWRIGHT_DRIVER_PATH", playrightDriver);55#else56 Console.WriteLine($"Skipping setting PLAYWRIGHT_BROWSERS_PATH");57#endif58 Console.WriteLine($"Creating nuget restore directory: {nugetRestore}");59 Directory.CreateDirectory(nugetRestore);60 // Rename default.runner.json to xunit.runner.json if there is not a custom one from the project61 if (!File.Exists("xunit.runner.json"))62 {63 File.Copy("default.runner.json", "xunit.runner.json");64 }65 DisplayContents(Path.Combine(Options.DotnetRoot, "host", "fxr"));66 DisplayContents(Path.Combine(Options.DotnetRoot, "shared", "Microsoft.NETCore.App"));67 DisplayContents(Path.Combine(Options.DotnetRoot, "shared", "Microsoft.AspNetCore.App"));68 DisplayContents(Path.Combine(Options.DotnetRoot, "packs", "Microsoft.AspNetCore.App.Ref"));69 return true;70 }71 catch (Exception e)72 {73 Console.WriteLine($"Exception in SetupEnvironment: {e.ToString()}");74 return false;75 }76 }77 public void DisplayContents(string path = "./")78 {79 try80 {81 Console.WriteLine();82 Console.WriteLine($"Displaying directory contents for {path}:");83 foreach (var file in Directory.EnumerateFiles(path))84 {85 Console.WriteLine(Path.GetFileName(file));86 }87 foreach (var file in Directory.EnumerateDirectories(path))88 {89 Console.WriteLine(Path.GetFileName(file));90 }91 Console.WriteLine();92 }93 catch (Exception e)94 {95 Console.WriteLine($"Exception in DisplayContents: {e.ToString()}");96 }97 }98#if INSTALLPLAYWRIGHT99 public async Task<bool> InstallPlaywrightAsync()100 {101 try102 {103 Console.WriteLine($"Installing Playwright to Browsers: {Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH")} Driver: {Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_PATH")}");104 await Playwright.InstallAsync(Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH"), Environment.GetEnvironmentVariable("PLAYWRIGHT_DRIVER_PATH"));105 DisplayContents(Environment.GetEnvironmentVariable("PLAYWRIGHT_BROWSERS_PATH"));106 return true;107 }108 catch (Exception e)109 {110 Console.WriteLine($"Exception installing playwright: {e.ToString()}");111 return false;112 }113 }114#endif115 public async Task<bool> InstallDotnetToolsAsync()116 {117 try118 {...
NUnitPlaywrightBase.cs
Source: NUnitPlaywrightBase.cs
1using Microsoft.Extensions.Configuration;2using Microsoft.Playwright;3using NUnit.Framework;4using NUnit.Framework.Interfaces;5using System;6using System.IO;7using System.Threading.Tasks;8namespace PlaywrightCSharp9{10 [TestFixture]11 public abstract class NUnitPlaywrightBase12 {13 protected IPlaywright playwright;14 protected IBrowser browser;15 protected IPage page;16 protected IBrowserContext context;17 private string CurrentTestFolder = TestContext.CurrentContext.TestDirectory;18 private DirectoryInfo LogsFolder;19 private DirectoryInfo ScreenshotsFolder;20 [OneTimeSetUp]21 public void CreateiPlaywrightAndiBrowserContextInstances()22 {23 var config = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddJsonFile("appsettings.json").Build();24 var section = config.GetSection(nameof(PlaywrightBrowserSettings));25 var playwrightConfig = section.Get<PlaywrightBrowserSettings>();26 CurrentTestFolder = string.IsNullOrEmpty(playwrightConfig.LogFolderPath) ? CurrentTestFolder : playwrightConfig.LogFolderPath;27 LogsFolder = Directory.CreateDirectory(Path.Combine(CurrentTestFolder, "Logs"));28 ScreenshotsFolder = Directory.CreateDirectory(Path.Combine(CurrentTestFolder, "Screenshots"));29 LaunchBrowser(playwrightConfig.Browser, playwrightConfig.Headless);30 }31 [SetUp]32 public async Task CreateiBrowserContextAndiPageContextInstances()33 {34 context = await browser.NewContextAsync();35 page = await context.NewPageAsync();36 await page.SetViewportSizeAsync(1920, 1080);37 } 38 [TearDown]39 public async Task DisposeiPageContextAndiBrowserContextInstances()40 {41 var testResult = TestContext.CurrentContext.Result.Outcome;42 // Take screenshot and log the test results to a log file if the test fails.43 if (testResult.Status.Equals(TestStatus.Failed) || testResult.Status.Equals(ResultState.Error))44 {45 var testSpecificScreenshotFolder = Directory.CreateDirectory(Path.Combine(ScreenshotsFolder.FullName, TestContext.CurrentContext.Test.Name));46 var screenshotPath = Path.Combine(testSpecificScreenshotFolder.FullName, $"TestFailure_{DateTime.Now.ToString("yyyyMMddHHmmss")}.png");47 //Take a screenshot48 await page.ScreenshotAsync(new PageScreenshotOptions { Path = screenshotPath });49 //var testSpecificLogsFolder = Directory.CreateDirectory(Path.Combine(LogsFolder.FullName, TestContext.CurrentContext.Test.Name));50 }51 //await page.CloseAsync();52 await context.CloseAsync();53 }54 [OneTimeTearDown]55 public void DisposeiBrowserContextAndiPlaywrightContextInstances()56 {57 //await page.CloseAsync();58 //await browser.CloseAsync();59 playwright?.Dispose();60 }61 #region Private Methods 62 private void LaunchBrowser(string browsertype, bool headless = false)63 {64 if (browser == null)65 {66 if (headless == false)67 {68 browser = Task.Run(() => GetBrowserAsync(browsertype, headless: false)).Result; 69 }70 else71 {72 browser = Task.Run(() => GetBrowserAsync(browsertype, headless: true)).Result;73 }74 }75 }76 private async Task<IBrowser> GetBrowserAsync(string browserName, bool headless = false)77 {78 var playwright = await Playwright.CreateAsync();79 IBrowser browser;80 switch (browserName)81 {82 case "chrome":83 if (headless)84 {85 browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = true });86 }87 else88 {89 browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Channel = browserName, Headless = false, SlowMo = 1000 });90 }91 break;92 case "msedge":...
WebHostServerFixture.cs
Source: WebHostServerFixture.cs
...3using Microsoft.AspNetCore.Hosting.Server.Features;4using Microsoft.AspNetCore.TestHost;5using Microsoft.Extensions.DependencyInjection;6using Microsoft.Extensions.Hosting;7using PlaywrightSharp;8using Serilog;9using Serilog.Events;10using System;11using System.IO;12using System.Linq;13using System.Runtime.ExceptionServices;14using System.Threading;15using System.Threading.Tasks;16using Xunit;17namespace PlaywrightFeatureTest.Infrastructure18{19 [CollectionDefinition(TestConstants.TestFixtureBrowserCollectionName, DisableParallelization = true)]20 public class ShareWebserver : ICollectionFixture<WebHostServerFixture>21 {22 }23 public class WebHostServerFixture : IDisposable, IAsyncLifetime24 {25 internal static IPlaywright Playwright { get; private set; }26 internal static IBrowser Browser { get; private set; }27 private readonly Lazy<Uri> _rootUriInitializer;28 public Uri RootUri => _rootUriInitializer.Value;29 public IHost Host { get; set; }30 public WebHostServerFixture()31 {32 _rootUriInitializer = new Lazy<Uri>(() => new Uri(StartAndGetRootUri()));33 }34 protected static void RunInBackgroundThread(Action action)35 {36 using var isDone = new ManualResetEvent(false);37 ExceptionDispatchInfo edi = null;38 new Thread(() =>39 {40 try41 {42 action();43 }44 catch (Exception ex)45 {46 edi = ExceptionDispatchInfo.Capture(ex);47 }48 isDone.Set();49 }).Start();50 if (!isDone.WaitOne(TimeSpan.FromSeconds(150)))51 throw new TimeoutException("Timed out waiting for: " + action);52 if (edi != null)53 throw edi.SourceException;54 }55 protected string StartAndGetRootUri()56 {57 // As the port is generated automatically, we can use IServerAddressesFeature to get the actual server URL58 Host = CreateWebHost();59 RunInBackgroundThread(Host.Start);60 return Host.Services.GetRequiredService<IServer>().Features61 .Get<IServerAddressesFeature>()62 .Addresses.FirstOrDefault();63 }64 /// <inheritdoc/>65 public Task InitializeAsync() => LaunchBrowserAsync();66 /// <inheritdoc/>67 public Task DisposeAsync() => ShutDownAsync();68 private async Task LaunchBrowserAsync()69 {70 try71 {72 Playwright = await PlaywrightSharp.Playwright.CreateAsync(TestConstants.LoggerFactory, debug: "pw*");73 Browser = await Playwright[TestConstants.Product].LaunchAsync(TestConstants.GetDefaultBrowserOptions());74 }75 catch (Exception ex)76 {77 Console.WriteLine(ex);78 throw new Exception("Launch failed", ex);79 }80 }81 internal async Task ShutDownAsync()82 {83 try84 {85 await Browser.CloseAsync();86 Playwright.Dispose();87 }88 catch (Exception ex)89 {90 Console.WriteLine(ex);91 throw new Exception("Shutdown failed", ex);92 }93 }94 public void Dispose()95 {96 Host?.Dispose();97 Host?.StopAsync();98 }99 protected IHost CreateWebHost()100 {101 var osPath = Path.DirectorySeparatorChar;102 var path = $"..{osPath}..{osPath}"; 103 104 Log.Logger = new LoggerConfiguration()105 .MinimumLevel.Debug()106 .MinimumLevel.Override("Microsoft", LogEventLevel.Information)107 .Enrich.FromLogContext()108 .WriteTo.Console()109 .CreateLogger();110 var host = new HostBuilder()111 .ConfigureWebHost(webHostBuilder => webHostBuilder112 .UseKestrel()113 .UseSolutionRelativeContentRoot(path, "AspnetPlaywrightFeatureTest.sln") 114 .UseStaticWebAssets()115 .UseStartup<WebUnderTest.Startup>()116 .UseSerilog() 117 .UseUrls($"http://127.0.0.1:0"))118 .Build();119 return host;120 }121 }122}...
BasedPdfController.cs
Source: BasedPdfController.cs
...8using Microsoft.AspNetCore.Mvc.Rendering;9using Microsoft.AspNetCore.Routing;10using Microsoft.Extensions.DependencyInjection;11using Microsoft.Extensions.Options;12using PlaywrightSharp;13namespace ProjectF.Api.Features.PdfGenerator14{15 public class BasePdfController : Controller16 {17 private static readonly Task playwrightInstall;18 static BasePdfController()19 {20 playwrightInstall = Playwright.InstallAsync();21 }22 protected Task<FileContentResult> Pdf() => Pdf(View());23 protected Task<FileContentResult> Pdf(string viewName) => Pdf(View(viewName));24 protected Task<FileContentResult> Pdf(object model) => Pdf(View(model));25 protected Task<FileContentResult> Pdf(string viewName, object model) => Pdf(View(viewName, model));26 protected async Task<FileContentResult> Pdf(ViewResult result)27 {28 await playwrightInstall;29 using var playwright = await Playwright.CreateAsync();30 await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions31 {32 Headless = true33 });34 var page = await browser.NewPageAsync();35 var html = await GetHtml(result);36 await page.SetContentAsync(html);37 var pdf = await page.GetPdfAsync();38 return File(pdf, "application/pdf");39 }40 private async Task<string> GetHtml(ViewResult result)41 {42 // Get html from the result.43 // https://weblogs.asp.net/ricardoperes/getting-html-for-a-viewresult-in-asp-net-core...
PlaywrightFixture.cs
Source: PlaywrightFixture.cs
1using System;2using Microsoft.Playwright;3namespace xUnitTests.Framework4{5 public class PlaywrightFixture : IPlaywrightFixture6 {7 private readonly IConfiguration _configuration;8 public IBrowser Browser { get; }9 public IPlaywright Playwright { get; }10 public IBrowserType BrowserType { get; }11 public IBrowserContext Context12 {13 get14 {15 var context = Browser.NewContextAsync().Result;16 context.SetDefaultNavigationTimeout(_configuration.DefaultTimeout);17 context.SetDefaultTimeout(_configuration.DefaultTimeout);18 return context;19 }20 }21 public PlaywrightFixture(IConfiguration configuration)22 {23 _configuration = configuration;24 Playwright = Microsoft.Playwright.Playwright.CreateAsync().Result;25 BrowserType = Playwright[_configuration.BrowserName];26 Browser = BrowserType.LaunchAsync(new BrowserTypeLaunchOptions27 {28 Headless = _configuration.Headless,29 SlowMo = _configuration.SlowMo,30 }).Result;31 32 }33 private bool _disposedValue;34 public virtual void Dispose(bool disposing)35 {36 if (!_disposedValue)37 {38 if (disposing)39 {40 Playwright.Dispose();41 }42 _disposedValue = true;43 }44 }45 public void Dispose()46 {47 Dispose(disposing: true);48 GC.SuppressFinalize(this);49 }50 }51}...
Fixture.cs
Source: Fixture.cs
1using Microsoft.Playwright;2using System;3namespace pw4{5 public partial class BaseTestContextClass : IDisposable6 {7 private readonly IConfiguration _configuration;8 protected IBrowser Browser { get; private set; }9 protected IPlaywright Playwright { get; private set; }10 protected IBrowserType BrowserType { get; set; }11 protected IBrowserContext Context { get; set; }12 public BaseTestContextClass(IConfiguration configuration)13 {14 _configuration = configuration;15 Playwright = Microsoft.Playwright.Playwright.CreateAsync().Result;16 BrowserType = Playwright[_configuration.BrowserName];17 Browser = BrowserType.LaunchAsync(new BrowserTypeLaunchOptions18 {19 Headless = _configuration.Headless,20 SlowMo = _configuration.SlowMo,21 }).Result;22 23 24 }25 private bool _disposedValue;26 protected virtual void Dispose(bool disposing)27 {28 if (!_disposedValue)29 {30 if (disposing)31 {32 Playwright.Dispose();33 }34 35 _disposedValue = true;36 }37 }38 public void Dispose()39 {40 Dispose(disposing: true);41 GC.SuppressFinalize(this);42 }43 }44}...
PlaywrightDriver.cs
Source: PlaywrightDriver.cs
1using Microsoft.Playwright;2using PlaywrightTests.Models;3using System.Threading.Tasks;4namespace PlaywrightTests.WebDriver5{6 public class PlaywrightDriver7 {8 public async Task<IPage> CreatePlaywright(BrowserType inBrowser, BrowserTypeLaunchOptions inLaunchOptions)9 {10 var playwright = await Playwright.CreateAsync();11 IBrowser browser = null;12 if (inBrowser == BrowserType.Chromium)13 {14 browser = await playwright.Chromium.LaunchAsync(inLaunchOptions);15 }16 17 if (inBrowser == BrowserType.Firefox)18 {19 browser = await playwright.Firefox.LaunchAsync(inLaunchOptions);20 }21 if (inBrowser == BrowserType.WebKit)22 {23 browser = await playwright.Webkit.LaunchAsync(inLaunchOptions);24 }...
BrowserExtensions.cs
Source: BrowserExtensions.cs
1using Microsoft.Playwright;2namespace IkeaBot.Extensions;3public static class BrowserExtensions4{5 public static async Task<IBrowser> LauncChromeAsync(this IPlaywright playwright)6 {7 var options = new BrowserTypeLaunchOptions8 {9 Headless = true10 };11 try12 {13 return await playwright.Chromium.LaunchAsync(options);14 }15 catch16 {17 Microsoft.Playwright.Program.Main(new[] { "install" });18 return await playwright.Chromium.LaunchAsync(options);19 }20 }21}...
Playwright
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.IO;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 using var playwright = await Playwright.CreateAsync();10 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var page = await browser.NewPageAsync();14 await page.ScreenshotAsync(new PageScreenshotOptions15 {16 Path = Path.Combine(Directory.GetCurrentDirectory(), "google.png")17 });18 await page.CloseAsync();19 await browser.CloseAsync();20 }21 }22}23using Microsoft.Playwright;24using System;25using System.IO;26using System.Threading.Tasks;27{28 {29 static async Task Main(string[] args)30 {31 using var playwright = await Playwright.CreateAsync();32 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions33 {34 });35 var page = await browser.NewPageAsync();36 await page.ScreenshotAsync(new PageScreenshotOptions37 {38 Path = Path.Combine(Directory.GetCurrentDirectory(), "google.png")39 });40 await page.CloseAsync();41 await browser.CloseAsync();42 }43 }44}45using Microsoft.Playwright;46using System;47using System.IO;48using System.Threading.Tasks;49{50 {51 static async Task Main(string[] args)52 {53 using var playwright = await Playwright.CreateAsync();54 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions55 {
Playwright
Using AI Code Generation
1using Microsoft.Playwright;2using Microsoft.Playwright.NUnit;3using NUnit.Framework;4using System;5using System.Threading.Tasks;6{7 {8 public async Task Test1()9 {10 using var playwright = await Playwright.CreateAsync();11 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions12 {13 });14 var page = await browser.NewPageAsync();15 await page.ScreenshotAsync("google.png");16 }17 }18}
Playwright Multiple Elements - Is there an equivalent to Selenium FindElements?
How to handle multiple file downloads in Playwright?
Run Playwright.NET tests in Docker container
How to handle multiple file downloads in Playwright?
Running playwright in headed mode C#
Playwright (.NET) tries to use different browser versions than installed
Playwright "Element is not attached to the DOM"
Playwright Multiple Elements - Is there an equivalent to Selenium FindElements?
Microsoft.Playwright.PlaywrightException : unable to verify the first certificate Using Playwright C# While connecting Moon
How do you create a global configuration for Playwright .NET?
Using a selector that finds a list of locators in Playwright is exactly the same as calling .FindElements() in selenium, except that Playwright does not have a specifically named method like .FindLocators().
Playwright - a selector that matches multiple elements returns a list of locators, which you then iterate over:
var rows = page.GetByRole(AriaRole.Listitem);
var count = await rows.CountAsync();
for (int i = 0; i < count; ++i)
Console.WriteLine(await rows.Nth(i).TextContentAsync());
Selenium - FindElements returns a list of elements that you have to iterate over.
IList < IWebElement > elements = driver.FindElements(By.TagName("p"));
foreach(IWebElement e in elements) {
System.Console.WriteLine(e.Text);
}
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!