Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Selectors
Job.cs
Source:Job.cs
...100 await entry.Page.GotoAsync(entry.Url);101 }102103 // Wait for selectors?104 if (entry.WaitForSelectors != null)105 {106 foreach (var selector in entry.WaitForSelectors)107 {108 await entry.Page.WaitForSelectorAsync(selector);109 }110 }111112 // Wait for functions?113 if (entry.WaitForFunctions != null)114 {115 foreach (var function in entry.WaitForFunctions)116 {117 await entry.Page.WaitForFunctionAsync(function);118 }119 }120121 // Render to byte-array.122 entry.PdfBytes = await entry.Page.PdfAsync();123 }124125 // Merge PDFs.126 if (instructions.Entries.Count > 1)127 {128 using var pdfDoc = new PdfDocument();129130 foreach (var entry in instructions.Entries)131 {132 var ms = new MemoryStream(entry.PdfBytes);133 var doc = PdfReader.Open(ms, PdfDocumentOpenMode.Import);134135 for (var i = 0; i < doc.PageCount; i++)136 {137 pdfDoc.AddPage(doc.Pages[i]);138 }139 }140141 await using var output = new MemoryStream();142143 pdfDoc.Save(output, true);144 this.JobFinishedBytes = output.ToArray();145 }146 else147 {148 this.JobFinishedBytes = instructions.Entries[0].PdfBytes;149 }150 }151152 #endregion153154 #region Helper classes155156 public class Instructions157 {158 /// <summary>159 /// Entries to be rendered.160 /// </summary>161 public List<RenderEntry> Entries { get; set; }162163 /// <summary>164 /// Webhooks to call for various job statuses.165 /// </summary>166 public WebHooksWrapper WebHooks { get; set; }167168 /// <summary>169 /// Email to send for various job statuses.170 /// </summary>171 public EmailHookWrapper EmailHooks { get; set; }172173 public class RenderEntry174 {175 /// <summary>176 /// HTML to render.177 /// </summary>178 public string Html { get; set; }179180 /// <summary>181 /// URL to render.182 /// </summary>183 public string Url { get; set; }184185 /// <summary>186 /// Wait for CSS selectors.187 /// </summary>188 public string[] WaitForSelectors { get; set; }189190 /// <summary>191 /// Wait for JavaScript functions.192 /// </summary>193 public string[] WaitForFunctions { get; set; }194195 /// <summary>196 /// Playwright page.197 /// </summary>198 public IPage Page { get; set; }199200 /// <summary>201 /// Rendered PDF, as bytes.202 /// </summary>
...
Browser.cs
Source:Browser.cs
...98 userAgent: options.UserAgent,99 viewportSize: options.ViewportSize,100 screenSize: options.ScreenSize,101 baseUrl: options.BaseURL,102 strictSelectors: options.StrictSelectors,103 forcedColors: options.ForcedColors).ConfigureAwait(false)).Object;104 context.Options = options;105 ((Tracing)context.Tracing).LocalUtils = LocalUtils;106 BrowserContextsList.Add(context);107 return context;108 }109 public async Task<IPage> NewPageAsync(BrowserNewPageOptions options = default)110 {111 options ??= new();112 var contextOptions = new BrowserNewContextOptions()113 {114 AcceptDownloads = options.AcceptDownloads,115 IgnoreHTTPSErrors = options.IgnoreHTTPSErrors,116 BypassCSP = options.BypassCSP,117 ViewportSize = options.ViewportSize,118 ScreenSize = options.ScreenSize,119 UserAgent = options.UserAgent,120 DeviceScaleFactor = options.DeviceScaleFactor,121 IsMobile = options.IsMobile,122 HasTouch = options.HasTouch,123 JavaScriptEnabled = options.JavaScriptEnabled,124 TimezoneId = options.TimezoneId,125 Geolocation = options.Geolocation,126 Locale = options.Locale,127 Permissions = options.Permissions,128 ExtraHTTPHeaders = options.ExtraHTTPHeaders,129 Offline = options.Offline,130 HttpCredentials = options.HttpCredentials,131 ColorScheme = options.ColorScheme,132 ReducedMotion = options.ReducedMotion,133 ForcedColors = options.ForcedColors,134 RecordHarPath = options.RecordHarPath,135 RecordHarOmitContent = options.RecordHarOmitContent,136 RecordVideoDir = options.RecordVideoDir,137 RecordVideoSize = options.RecordVideoSize,138 Proxy = options.Proxy,139 StorageState = options.StorageState,140 StorageStatePath = options.StorageStatePath,141 BaseURL = options.BaseURL,142 StrictSelectors = options.StrictSelectors,143 };144 var context = (BrowserContext)await NewContextAsync(contextOptions).ConfigureAwait(false);145 var page = (Page)await context.NewPageAsync().ConfigureAwait(false);146 page.OwnedContext = context;147 context.Options = contextOptions;148 context.OwnerPage = page;149 return page;150 }151 public ValueTask DisposeAsync() => new ValueTask(CloseAsync());152 internal static Dictionary<string, object> GetVideoArgs(string recordVideoDir, RecordVideoSize recordVideoSize)153 {154 Dictionary<string, object> recordVideoArgs = null;155 if (recordVideoSize != null && string.IsNullOrEmpty(recordVideoDir))156 {...
BrowserChannel.cs
Source:BrowserChannel.cs
...73 string userAgent = null,74 ViewportSize viewportSize = default,75 ScreenSize screenSize = default,76 string baseUrl = default,77 bool? strictSelectors = default)78 {79 var args = new Dictionary<string, object>80 {81 { "acceptDownloads", acceptDownloads },82 { "bypassCSP", bypassCSP },83 { "colorScheme", colorScheme },84 { "reducedMotion", reducedMotion },85 { "deviceScaleFactor", deviceScaleFactor },86 };87 if (extraHTTPHeaders != null)88 {89 args["extraHTTPHeaders"] = extraHTTPHeaders.Select(kv => new HeaderEntry { Name = kv.Key, Value = kv.Value }).ToArray();90 }91 args.Add("geolocation", geolocation);92 args.Add("hasTouch", hasTouch);93 args.Add("httpCredentials", httpCredentials);94 args.Add("ignoreHTTPSErrors", ignoreHTTPSErrors);95 args.Add("isMobile", isMobile);96 args.Add("javaScriptEnabled", javaScriptEnabled);97 args.Add("locale", locale);98 args.Add("offline", offline);99 args.Add("permissions", permissions);100 args.Add("proxy", proxy);101 args.Add("strictSelectors", strictSelectors);102 args.Add("forcedColors", forcedColors);103 if (!string.IsNullOrEmpty(recordHarPath))104 {105 args.Add("recordHar", new106 {107 Path = recordHarPath,108 OmitContent = recordHarOmitContent,109 });110 }111 if (recordVideo != null)112 {113 args.Add("recordVideo", recordVideo);114 }115 if (!string.IsNullOrEmpty(storageStatePath))...
PlaywrightImpl.cs
Source:PlaywrightImpl.cs
...61 IChannel<PlaywrightImpl> IChannelOwner<PlaywrightImpl>.Channel => _channel;62 public IBrowserType Chromium { get => _initializer.Chromium; set => throw new NotSupportedException(); }63 public IBrowserType Firefox { get => _initializer.Firefox; set => throw new NotSupportedException(); }64 public IBrowserType Webkit { get => _initializer.Webkit; set => throw new NotSupportedException(); }65 public ISelectors Selectors => _initializer.Selectors;66 public IReadOnlyDictionary<string, BrowserNewContextOptions> Devices => _devices;67 internal Connection Connection { get; set; }68 internal Browser PreLaunchedBrowser => _initializer.PreLaunchedBrowser;69 internal LocalUtils Utils { get; set; }70 /// <summary>71 /// Gets a <see cref="IBrowserType"/>.72 /// </summary>73 /// <param name="browserType"><see cref="IBrowserType"/> name. You can get the names from <see cref="global::Microsoft.Playwright.BrowserType"/>.74 /// e.g.: <see cref="global::Microsoft.Playwright.BrowserType.Chromium"/>,75 /// <see cref="global::Microsoft.Playwright.BrowserType.Firefox"/> or <see cref="global::Microsoft.Playwright.BrowserType.Webkit"/>.76 /// </param>77 public IBrowserType this[string browserType]78 => browserType?.ToLower() switch79 {...
SelectorsChannelImpl.cs
Source:SelectorsChannelImpl.cs
...35using Microsoft.Playwright.Helpers;36#nullable enable37namespace Microsoft.Playwright.Transport.Channels38{39 internal class SelectorsChannelImpl : Channel<Selectors>40 {41 public SelectorsChannelImpl(string guid, Connection connection, Selectors owner) : base(guid, connection, owner)42 {43 }44 internal virtual async Task RegisterAsync(string name,45 string source,46 bool? contentScript)47 => await Connection.SendMessageToServerAsync<JsonElement>(48 Guid,49 "register",50 new51 {52 name = name,53 source = source,54 contentScript = contentScript,55 }56 )57 .ConfigureAwait(false);58 }59 internal partial class SelectorsChannel : SelectorsChannelImpl60 {61 public SelectorsChannel(string guid, Connection connection, Selectors owner) : base(guid, connection, owner)62 {63 }64 }65}66#nullable disable...
Selectors.cs
Source:Selectors.cs
...25using Microsoft.Playwright.Transport;26using Microsoft.Playwright.Transport.Channels;27namespace Microsoft.Playwright.Core28{29 internal class Selectors : ChannelOwnerBase, IChannelOwner<Selectors>, ISelectors30 {31 private readonly SelectorsChannel _channel;32 internal Selectors(IChannelOwner parent, string guid) : base(parent, guid)33 {34 _channel = new(guid, parent.Connection, this);35 }36 ChannelBase IChannelOwner.Channel => _channel;37 IChannel<Selectors> IChannelOwner<Selectors>.Channel => _channel;38 public async Task RegisterAsync(string name, SelectorsRegisterOptions options = default)39 {40 options ??= new SelectorsRegisterOptions();41 var script = ScriptsHelper.EvaluationScript(options?.Script, options?.Path);42 await _channel.RegisterAsync(name, script, options?.ContentScript).ConfigureAwait(false);43 }44 }45}...
BlazorWASMPlaywrightTests.cs
Source:BlazorWASMPlaywrightTests.cs
...24 var browser = await GetBrowser();25 var page = await browser.NewPageAsync();26 await page.GotoAsync(_server.RootUri + "counter", new PageGotoOptions() { WaitUntil = WaitUntilState.NetworkIdle });27 await page.ClickAsync("#IncrementBtn");28 // Selectors are not only CSS selectors. You can use xpath, css, or text selectors29 // By default there is a timeout of 30s. If the selector isn't found after the timeout, an exception is thrown.30 // More about selectors: https://playwright.dev/#version=v1.4.2&path=docs%2Fselectors.md31 await page.WaitForSelectorAsync("text=Current count: 1");32 await browser.CloseAsync();33 }34 public static async Task<IBrowser> GetBrowser()35 {36 var playwright = await Playwright.CreateAsync();37 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions()38 {39 Headless = false,40 SlowMo = 500041 });42 return browser;...
PlaywrightInitializer.cs
Source:PlaywrightInitializer.cs
...30 public Core.BrowserType Firefox { get; set; }31 public Core.BrowserType Webkit { get; set; }32 public Core.LocalUtils Utils { get; set; }33 public List<DeviceDescriptorEntry> DeviceDescriptors { get; set; }34 public Core.Selectors Selectors { get; set; }35 public Core.Browser PreLaunchedBrowser { get; set; }36 public Core.SocksSupport SocksSupport { get; set; }37 }38}
Selectors
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 static async Task Main()6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync();9 var page = await browser.NewPageAsync();10 var element = await page.QuerySelectorAsync("input[name=search]");11 await element.TypeAsync("Playwright");12 await element.PressAsync("Enter");13 await page.ScreenshotAsync("screenshot.png");14 }15}16using Microsoft.Playwright;17using System;18using System.Threading.Tasks;19{20 static async Task Main()21 {22 using var playwright = await Playwright.CreateAsync();23 await using var browser = await playwright.Chromium.LaunchAsync();24 var page = await browser.NewPageAsync();25 var element = await page.QuerySelectorAsync("input[name=search]");26 await element.TypeAsync("Playwright");27 await element.PressAsync("Enter");28 await page.ScreenshotAsync("screenshot.png");29 }30}31using Microsoft.Playwright;32using System;33using System.Threading.Tasks;34{35 static async Task Main()36 {37 using var playwright = await Playwright.CreateAsync();38 await using var browser = await playwright.Chromium.LaunchAsync();39 var page = await browser.NewPageAsync();40 var element = await page.QuerySelectorAsync("input[name=search]");41 await element.TypeAsync("Playwright");42 await element.PressAsync("Enter");43 await page.ScreenshotAsync("screenshot.png");44 }45}46using Microsoft.Playwright;47using System;48using System.Threading.Tasks;49{50 static async Task Main()51 {52 using var playwright = await Playwright.CreateAsync();53 await using var browser = await playwright.Chromium.LaunchAsync();54 var page = await browser.NewPageAsync();
Selectors
Using AI Code Generation
1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 static async Task Main(string[] args)11 {12 using var playwright = await Playwright.CreateAsync();13 await using var browser = await playwright.Chromium.LaunchAsync();14 var page = await browser.NewPageAsync();15 var input = await page.QuerySelectorAsync("input[title='Search']");16 await input.TypeAsync("Hello World");17 var button = await page.QuerySelectorAsync("input[value='Google Search']");18 await button.ClickAsync();19 }20 }21}
Selectors
Using AI Code Generation
1using Microsoft.Playwright.Core;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await Playwright.InstallAsync();9 using var playwright = await Playwright.CreateAsync();10 using var browser = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });11 var context = await browser.NewContextAsync(new BrowserNewContextOptions { IgnoreHTTPSErrors = true });12 var page = await context.NewPageAsync();13 await page.ClickAsync("text=Sign in");14 await page.ClickAsync("input[name=\"identifier\"]");15 await page.TypeAsync("input[name=\"identifier\"]", "
Selectors
Using AI Code Generation
1using Microsoft.Playwright;2using Microsoft.Playwright.Core;3using Microsoft.Playwright.Helpers;4using System;5using System.Collections.Generic;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9{10 {11 static async Task Main(string[] args)12 {13 using var playwright = await Playwright.CreateAsync();14 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });15 var context = await browser.NewContextAsync();16 var page = await context.NewPageAsync();17 await page.ClickAsync("text=Google apps");18 await page.ClickAsync("text=Search se
Selectors
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4using Microsoft.Playwright.Core;5{6 {7 static async Task Main(string[] args)8 {9 var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync(headless: false);11 var page = await browser.NewPageAsync();12 await page.ClickAsync("text=English");13 await page.ClickAsync("text=Log in");14 await page.TypeAsync("input[name='wpName']", "username");15 await page.TypeAsync("input[name='wpPassword']", "password");16 await page.ClickAsync("input[type='submit']");17 await page.ClickAsync("text=Log out");18 await browser.CloseAsync();19 }20 }21}
Selectors
Using AI Code Generation
1{2 public static string XPath(string selector) { throw null; }3 public static string Text(string selector) { throw null; }4 public static string Css(string selector) { throw null; }5 public static string Shadow(string selector) { throw null; }6 public static string Fill(string selector) { throw null; }7 public static string TextEquals(string selector) { throw null; }8 public static string TextMatches(string selector) { throw null; }
Selectors
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {
Selectors
Using AI Code Generation
1using Microsoft.Playwright.Core;2using Microsoft.Playwright.Core.Selectors;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var selectorEngine = new SelectorEngine();10 selectorEngine.AddSelector("myselector", "myselector", (node, selector, options) =>11 {12 return Task.FromResult(node);13 });14 var browser = await Microsoft.Playwright.Core.Playwright.CreateBrowserAsync();15 var page = await browser.NewPageAsync();16 var element = await page.QuerySelectorAsync("myselector");17 await browser.CloseAsync();18 }19 }20}
Selectors
Using AI Code Generation
1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var playwright = await Playwright.CreateAsync();9 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var page = await browser.NewPageAsync();13 var element = await page.QuerySelectorAsync("input[name='q']");14 await element.TypeAsync("Microsoft");15 await element.PressAsync("Enter");16 await page.ScreenshotAsync("screenshot.png");17 await browser.CloseAsync();18 }19 }20}21using Microsoft.Playwright;22using System;23using System.Threading.Tasks;24{25 {26 static async Task Main(string[] args)27 {28 var playwright = await Playwright.CreateAsync();29 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions30 {31 });32 var page = await browser.NewPageAsync();33 var element = await page.QuerySelectorAsync("input[name='q']");34 await element.TypeAsync("Microsoft");35 await element.PressAsync("Enter");36 await page.ScreenshotAsync("screenshot.png");37 await browser.CloseAsync();38 }39 }40}41using Microsoft.Playwright;42using System;43using System.Threading.Tasks;44{45 {46 static async Task Main(string[] args)47 {48 var playwright = await Playwright.CreateAsync();49 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions50 {51 });52 var page = await browser.NewPageAsync();53 var element = await page.QuerySelectorAsync("input[name='q']");54 await element.TypeAsync("Microsoft");55 await element.PressAsync("Enter");
Selectors
Using AI Code Generation
1using Microsoft.Playwright.Core;2{3 public static string SelectorsClass()4 {5 return "Selectors";6 }7}8using System;9{10 {11 static void Main(string[] args)12 {13 Console.WriteLine("Hello World!");14 }15 }16}17using System;18{19 {20 static void Main(string[] args)21 {22 Console.WriteLine("Hello World!");23 }24 }25}26using System;27{28 {29 static void Main(string[] args)30 {31 Console.WriteLine("Hello World!");32 }33 }34}35using System;36{37 {38 static void Main(string[] args)39 {40 Console.WriteLine("Hello World!");41 }42 }43}
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!!