Best Playwright-dotnet code snippet using Microsoft.Playwright.PageGotoOptions.PageGotoOptions
Handlers.cs
Source:Handlers.cs
...12 var page = await browser.NewPageAsync();13 if (url.StartsWith('@')) {14 string at = url.Replace("@", "");15 // goto instabig16 await page.GotoAsync($"https://instabig.net/fullsize/{at}", new PageGotoOptions{17 WaitUntil = WaitUntilState.NetworkIdle18 });19 20 // get pfp21 var pfpSrc = await page.Locator("#fullsizeLink").GetAttributeAsync("href");22 // download23 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{at}{SetText.ResetAll}'s Instagram profile picture");24 await FileSystem.Download(pfpSrc, GetDownloadPath(folderPath, $"{at} insta pfp.png"));25 26 //exit27 await page.CloseAsync();28 return;29 }30 // get username31 await page.GotoAsync(url, new PageGotoOptions{32 WaitUntil = WaitUntilState.NetworkIdle33 });34 string? username = null;35 try { username = await page.Locator(".e1e1d > div:nth-child(1) > a:nth-child(1)").TextContentAsync(new LocatorTextContentOptions { Timeout = 1000 }); } catch {}36 if (string.IsNullOrEmpty(username)) username = "unknown";37 if (url.Contains("/p/")) {38 // goto page39 await page.GotoAsync("https://igdownloader.com/", new PageGotoOptions{40 WaitUntil = WaitUntilState.NetworkIdle41 });42 // search for post43 await page.TypeAsync(".ig[placeholder=\"ex: https://www.instagram.com/p/CBBp48HA8u7/\"]", url);44 await page.PressAsync(".ig[placeholder=\"ex: https://www.instagram.com/p/CBBp48HA8u7/\"]", "Enter");45 await page.WaitForRequestFinishedAsync();46 // get image src47 var downloads = await page.QuerySelectorAllAsync("a[class=download-button]");48 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{username}{SetText.ResetAll}'s Instagram post");49 for (int i = 0; i < downloads.Count; i++)50 {51 var downloadLink = downloads[i].GetAttributeAsync("href").Result.Replace("&dl=1", "");52 await FileSystem.Download(downloadLink, GetDownloadPath(folderPath, $"{username} slide {i} {new Random().Next(100, 999)}." + (downloadLink.Contains("dst-jpg") ? ".png" : ".mp4")));53 }54 //exit55 await page.CloseAsync();56 return;57 }58 //exit59 await page.CloseAsync();60 Output.Error("Action not supported");61 return;62 }63 public static async Task HandleDiscord(long userId, string folderPath) {64 // go to url65 using var playwright = await Playwright.CreateAsync();66 await using var browser = await playwright.Chromium.LaunchAsync( new BrowserTypeLaunchOptions { Headless = true });67 var page = await browser.NewPageAsync();68 await page.GotoAsync("https://discord.id", new PageGotoOptions{69 WaitUntil = WaitUntilState.NetworkIdle70 });71 // get user profile72 await page.TypeAsync("#inputid", userId.ToString());73 await page.ClickAsync("button.form-control");74 await page.ClickAsync(".frc-button");75 76 // get username77 string? username = null;78 try { username = await page.Locator("div.col-md-4:nth-child(2) > p:nth-child(3) > span:nth-child(3) > span:nth-child(1)").TextContentAsync(new LocatorTextContentOptions {79 Timeout = 300080 }); }81 catch { 82 try { username = await page.Locator("div.col-md-4.withdarker > p:nth-child(2) > span.resulth > span").TextContentAsync(new LocatorTextContentOptions {83 Timeout = 300084 }); }85 catch { username = "unknown"; } }86 // get pfp gif and png87 string? pfpSrc = null;88 try { pfpSrc = await page.Locator("img >> nth=0").GetAttributeAsync("src"); }89 catch {90 Output.Error("Failed to get User profile, keep in mind that Server IDs aren't supported");91 return;92 }93 var pfpDownloadPath = GetDownloadPath(folderPath, $"{username} pfp.png");94 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{username}{SetText.ResetAll}'s profile picture (PNG)");95 await FileSystem.Download(pfpSrc.Replace("?size=1024", "?size=2048"), pfpDownloadPath);96 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{username}{SetText.ResetAll}'s profile picture (GIF)");97 await FileSystem.Download(pfpSrc.Replace("?size=1024", "?size=2048").Replace(".png", ".gif"), pfpDownloadPath.Replace(".png", ".gif"));98 // get banner gif and png99 string? bannerSrc = null;100 try { bannerSrc = await page.QuerySelectorAsync("img[alt=\"Banner\"]").Result.GetAttributeAsync("src"); }101 catch {102 Output.Error("User doesn't have a banner");103 return;104 }105 var bannerDownloadPath = GetDownloadPath(folderPath, $"{username} banner.png");106 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{username}{SetText.ResetAll}'s banner (PNG)");107 await FileSystem.Download(bannerSrc.Replace("?size=1024", "?size=2048"), bannerDownloadPath);108 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{username}{SetText.ResetAll}'s banner (GIF)");109 await FileSystem.Download(bannerSrc.Replace("?size=1024", "?size=2048").Replace(".png", ".gif"), bannerDownloadPath.Replace(".png", ".gif"));110 // exit browser111 await page.CloseAsync();112 }113 public static async Task HandleYoutube(string url, string folderPath) {114 // go to url115 using var playwright = await Playwright.CreateAsync();116 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {117 IgnoreDefaultArgs = new string[] {"--mute-audio", "--user-gesture-required"}118 });119 var page = await browser.NewPageAsync();120 await page.GotoAsync(url, new PageGotoOptions{121 WaitUntil = WaitUntilState.NetworkIdle122 });123 124 // update link125 url = page.Url.Replace("&feature=youtu.be", "");126 // check if profile page or video127 if (url.Contains("watch?v=")) {128 // get video title129 var videoTitle = await page.Locator("yt-formatted-string.ytd-video-primary-info-renderer:nth-child(1)").TextContentAsync();130 // download thumbnail131 Output.Inform($"Downloading thumbnail for '{SetText.Blue}{SetText.Bold}{videoTitle}{SetText.ResetAll}'");132 // get original thumbnail link133 var videoId = url.Replace("https://", "").Replace("http://", "").Replace("www.youtube.com/watch?v=", "");134 var downloadLink = $"https://img.youtube.com/vi/{videoId}/maxresdefault.jpg";135 var downloadPath = GetDownloadPath(folderPath, $"{videoTitle}.png");136 await FileSystem.Download(downloadLink, downloadPath);137 }138 else if (url.Contains("/channel/") || url.Contains("/c/")) {139 // get channel name140 var channelName = await page.Locator("ytd-channel-name.ytd-c4-tabbed-header-renderer > div:nth-child(1) > div:nth-child(1) > yt-formatted-string:nth-child(1)").TextContentAsync();141 142 // download pfp143 Output.Inform($"Downloading {SetText.Blue}{SetText.Bold}{channelName}{SetText.ResetAll}'s YouTube profile picture");144 var pfp = await page.QuerySelectorAsync("#channel-header-container #img");145 var srcAttribute = await pfp.GetAttributeAsync("src");146 var pfpLink = srcAttribute.Replace("=s88-c-k-c0x00ffffff-no-rj", "");147 var downloadPath = GetDownloadPath(folderPath, $"{channelName} yt pfp.png");148 await FileSystem.Download(pfpLink, downloadPath);149 }150 else Output.Inform("Unrecognized link, only video and channel links are supported");151 // exit browser152 await page.CloseAsync();153 }154 public static async Task HandleSoundcloud(string url, string folderPath) {155 // go to url156 using var playwright = await Playwright.CreateAsync();157 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions {158 Headless = true159 });160 var page = await browser.NewPageAsync();161 await page.GotoAsync(url, new PageGotoOptions{162 WaitUntil = WaitUntilState.NetworkIdle163 });164 // check if profile page165 var profileStats = await page.QuerySelectorAsync("article[class=infoStats]");166 if (profileStats == null) {167 // get song & artist name168 var artistName = await page.Locator(".userBadge__usernameLink > span:nth-child(1)").TextContentAsync();169 var songName = await page.Locator("h1.soundTitle__title > span:nth-child(1)").TextContentAsync();170 // inform what we downloading171 Output.Inform($"Downloading artwork for '{SetText.Blue}{SetText.Bold}{songName}{SetText.ResetAll}' by {SetText.Blue}{SetText.Bold}{artistName}");172 // get original image url173 var styleAttribute = await page.Locator(".image__full").First.GetAttributeAsync("style");174 var substringStyleAttribute = styleAttribute.Substring(styleAttribute.IndexOf("https"));175 var imageUrl = substringStyleAttribute.Substring(0, substringStyleAttribute.IndexOf("\");"));...
Crawler.cs
Source:Crawler.cs
...40 int numberOfPagesToCrawl = int.Parse(Configuration[Constants.NumberOfPagesToCrawl]);41 var page = await BrowserContext.NewPageAsync().ConfigureAwait(false);42 string url = $"https://www.ah.nl/zoeken?query={System.Web.HttpUtility.UrlEncode(searchTerm)}&page={numberOfPagesToCrawl}";43 await page44 .GotoAsync(url, new PageGotoOptions { Timeout = 0 })45 .ConfigureAwait(false);46 var productElements = await page.QuerySelectorAllAsync("//*[@data-testhook='product-card']").ConfigureAwait(false);47 foreach (var productElement in productElements)48 {49 try50 {51 // Get all data in parallel and create a validated product52 var validatedProduct =53 CreateProduct()54 .Apply(GetProductTitle(productElement))55 .Apply(GetProductDescriptionAndId(productElement, Browser))56 .Apply(Return<string, Error>(merchantName))57 .Apply(GetPriceUnits(productElement))58 .Apply(GetPriceFraction(productElement))59 .Apply(GetImageSource(productElement))60 .Apply(GetUnit(productElement));61 switch (await validatedProduct)62 {63 case Ok<Product, Error>(var product):64 var result = IndexDocumentsAction.MergeOrUpload(product.ToIndexableProduct());65 await SearchClient.IndexDocumentsAsync(IndexDocumentsBatch.Create(result)).ConfigureAwait(false);66 break;67 case Error<Product, Error>(var error):68 Console.WriteLine($"Validation error : {error}");69 break;70 }71 }72 catch (Exception ex)73 {74 Console.WriteLine(ex.StackTrace);75 }76 }77 await page.CloseAsync().ConfigureAwait(false);78 }79 private static Task<Result<string, Error>> GetProductTitle(IElementHandle productElement) =>80 from productTitleElement in productElement.QuerySelector("css=[data-testhook='product-title']")81 from productTitle in productTitleElement.TextContent()82 select productTitle;83 private static Task<Result<string, Error>> GetPriceUnits(IElementHandle productElement) =>84 from priceUnitElement in productElement.QuerySelector("css=[class='price-amount_integer__1cJgL']")85 from priceUnit in priceUnitElement.TextContent()86 select priceUnit;87 private static Task<Result<string, Error>> GetPriceFraction(IElementHandle productElement) =>88 from priceFractionElement in productElement.QuerySelector("css=[class='price-amount_fractional__2wVIK']")89 from priceFraction in priceFractionElement.TextContent()90 select priceFraction;91 private static Task<Result<(string unitSize, string unitOfMeasure), Error>> GetUnit(IElementHandle productElement) =>92 from unitSizeElement in productElement.QuerySelector("css=[data-testhook='product-unit-size']")93 from unitSizeElementText in unitSizeElement.TextContent()94 let unitSizeParts = unitSizeElementText.Split(" ")95 let unitSize = unitSizeParts[0]96 let unitOfMeasure = unitSizeParts[1]97 select (unitSize, unitOfMeasure);98 private static Task<Result<string, Error>> GetImageSource(IElementHandle productElement) =>99 from imageSourceElement in productElement.QuerySelector("css=[data-testhook='product-image']")100 from imagesSource in imageSourceElement.GetAttribute("src")101 select imagesSource;102 private static Task<Result<(string id, string description), Error>> GetProductDescriptionAndId(IElementHandle productElement, IBrowser browser) =>103 from detailsPageElement in productElement.QuerySelector("css=a:first-child")104 from detailsPageLink in detailsPageElement.GetAttribute("href")105 from detailsContext in browser.NewContext(new BrowserNewContextOptions { })106 from detailsPage in detailsContext.NewPage()107 from _ in detailsPage.Goto($"https://www.ah.nl{detailsPageLink}", new PageGotoOptions { Timeout = 0 })108 from descriptionElement in detailsPage.QuerySelector("css=[data-testhook='product-summary']")109 from description in descriptionElement.TextContent()110 let id = detailsPageLink?.Split("/")[3]111 select (id, description);112 private static Task<Func<Result<string, Error>, Result<(string id, string description), Error>, Result<string, Error>, Result<string, Error>, Result<string, Error>, Result<string, Error>, Result<(string unitSize, string unitOfMeasure), Error>, Result<Product, Error>>> CreateProduct() =>113 Task.FromResult ((Result<string, Error> title, Result<(string id, string description), Error> idAndDescription, Result<string, Error> merchantName, Result<string, Error> priceUnits, Result<string, Error> priceFraction, Result<string, Error> imageSource, Result<(string unitSize, string unitOfMeasure), Error> unitSizeAndUnitOfMeasure) =>114 {115 var id = idAndDescription.Map(x => x.id);116 var description = idAndDescription.Map(y => y.description);117 var unitSize = unitSizeAndUnitOfMeasure.Map(x => x.unitSize);118 var unitOfMeasure = unitSizeAndUnitOfMeasure.Map(y => y.unitOfMeasure);119 var result = Ok<Func<string, string, string, string, string, string, string, string, string, Validated<Product>>, Error>(Product.Create)120 .Apply(id)121 .Apply(title)...
PageGotoOptions.cs
Source:PageGotoOptions.cs
...35using System.Threading.Tasks;36#nullable enable37namespace Microsoft.Playwright38{39 public class PageGotoOptions40 {41 public PageGotoOptions() { }42 public PageGotoOptions(PageGotoOptions clone)43 {44 if (clone == null)45 {46 return;47 }48 Referer = clone.Referer;49 Timeout = clone.Timeout;50 WaitUntil = clone.WaitUntil;51 }52 /// <summary>53 /// <para>54 /// Referer header value. If provided it will take preference over the referer header55 /// value set by <see cref="IPage.SetExtraHTTPHeadersAsync"/>.56 /// </para>...
BlazorWASMPlaywrightTests.cs
Source:BlazorWASMPlaywrightTests.cs
...22 public async Task Counter()23 {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 = 5000...
PlayWrightHtmlLoaderService.cs
Source:PlayWrightHtmlLoaderService.cs
...27 }28 public async Task<string> GetHtmlBodyAsync(string uri)29 {30 var page = await _browser.NewPageAsync();31 await page.GotoAsync(uri, new PageGotoOptions() { Timeout = 60000 });32 await page.WaitForLoadStateAsync(LoadState.NetworkIdle, new PageWaitForLoadStateOptions() { Timeout = 60000 });33 var htmlContent = await page.ContentAsync();34 await page.CloseAsync();35 return htmlContent;36 }37 }38}
PdfExporter.cs
Source:PdfExporter.cs
...19 await using var context = await browser.NewContextAsync();20 var page = await context.NewPageAsync();21 await page.EmulateMediaAsync(new PageEmulateMediaOptions {Media = Media.Print});22 var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(content));23 await page.GotoAsync($"data:text/html;base64,{encoded}", new PageGotoOptions {WaitUntil = WaitUntilState.NetworkIdle});24 await page.PdfAsync(new PagePdfOptions25 {26 Path = filePath,27 Format = "Letter",28 PrintBackground = true,29 Scale = 0.8f30 });31 }32 }33}
Extensions.cs
Source:Extensions.cs
...5using static Radix.Control.Result.Extensions;6namespace Radix.PlayWright.Page;7public static class Extensions8{9 public static Task<Result<IResponse, Error>> Goto(this IPage page, string url, PageGotoOptions pageGotoOptions) =>10 page.GotoAsync(url, pageGotoOptions)11 .Map2(12 faulted =>13 Error<IResponse, Error>($"Could not navigate to '{url}' because of {faulted.InnerException}"),14 succeeded =>15 Ok<IResponse, Error>(succeeded));16 public static Task<Result<IElementHandle, Error>> QuerySelector(this IPage page, string selector) =>17 from result in page.QuerySelectorAsync(selector)18 select result is not null19 ? Ok<IElementHandle, Error>(result)20 : Error<IElementHandle, Error>($"The selector '{selector}' yielded no result");21}...
BrowserManager.cs
Source:BrowserManager.cs
...10 return browser;11 }12 public async Task NavigateAsync(IPage page, string url)13 {14 await page.GotoAsync(url, new PageGotoOptions15 {16 WaitUntil = WaitUntilState.NetworkIdle,17 Timeout = 30000,18 });19 }20}...
PageGotoOptions
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions9 {10 });11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 {14 WaitUntil = new[] { WaitUntilState.Load },15 });16 }17 }18}
PageGotoOptions
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 {
PageGotoOptions
Using AI Code Generation
1var page = await browser.NewPageAsync();2{3 WaitUntil = new[] { WaitUntilState.Networkidle0 }4});5var page = await browser.NewPageAsync();6{7 WaitUntil = new[] { WaitUntilState.Networkidle0, WaitUntilState.Load }8});9var page = await browser.NewPageAsync();10{11 WaitUntil = new[] { WaitUntilState.Networkidle0, WaitUntilState.Load, WaitUntilState.DOMContentLoaded }12});13var page = await browser.NewPageAsync();14{15 WaitUntil = new[] { WaitUntilState.Networkidle0, WaitUntilState.Load, WaitUntilState.DOMContentLoaded, WaitUntilState.Networkidle2 }16});17var page = await browser.NewPageAsync();18{19 WaitUntil = new[] { WaitUntilState.Networkidle0, WaitUntilState.Load, WaitUntilState.DOMContentLoaded, WaitUntilState.Networkidle2, WaitUntilState.Networkidle }20});21var page = await browser.NewPageAsync();
PageGotoOptions
Using AI Code Generation
1var page = await context.NewPageAsync();2{3 WaitUntil = new[] { WaitUntilState.Networkidle }4});5var page = await context.NewPageAsync();6{7 WaitUntil = new[] { WaitUntilState.Load }8});9var page = await context.NewPageAsync();10{11 WaitUntil = new[] { WaitUntilState.DOMcontentloaded }12});13var page = await context.NewPageAsync();14{15 WaitUntil = new[] { WaitUntilState.Networkidle2 }16});17var page = await context.NewPageAsync();18{19 WaitUntil = new[] { WaitUntilState.Networkidle0 }20});21var page = await context.NewPageAsync();22{23 WaitUntil = new[] { WaitUntilState.Networkidle }24});25var page = await context.NewPageAsync();26{27 WaitUntil = new[] { WaitUntilState.Load
PageGotoOptions
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 static async Task Main(string[] args)6 {7 await using var playwright = await Playwright.CreateAsync();8 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 {13 });14 await page.ClickAsync("text=Images");15 await page.ClickAsync("text=Videos");16 await page.ClickAsync("text=News");17 await page.ClickAsync("text=Maps");18 await page.ClickAsync("text=More");19 await page.ClickAsync("text=Settings");20 await page.ClickAsync("text=History");21 await page.ClickAsync("text=Sign in");22 await page.ClickAsync("text=All");23 await page.ClickAsync("text=Images");24 await page.ClickAsync("text=Videos");25 await page.ClickAsync("text=News");26 await page.ClickAsync("text=Maps");27 await page.ClickAsync("text=More");28 await page.ClickAsync("text=Settings");29 await page.ClickAsync("text=History");30 await page.ClickAsync("text=Sign in");31 await page.ClickAsync("text=All");32 await page.ClickAsync("text=Images");33 await page.ClickAsync("text=Videos");34 await page.ClickAsync("text=News");35 await page.ClickAsync("text=Maps");36 await page.ClickAsync("text=More");37 await page.ClickAsync("text=Settings");38 await page.ClickAsync("text=History");39 await page.ClickAsync("text=Sign in");40 await page.ClickAsync("text=All");41 await page.ClickAsync("text=Images");42 await page.ClickAsync("text=Videos");43 await page.ClickAsync("text=News");44 await page.ClickAsync("text=Maps");45 await page.ClickAsync("text=More");46 await page.ClickAsync("text=Settings");47 await page.ClickAsync("text=History");48 await page.ClickAsync("text=Sign in");49 await page.ClickAsync("text=
PageGotoOptions
Using AI Code Generation
1using Microsoft.Playwright;2using System.Threading.Tasks;3{4 {5 public PageGotoOptions()6 {7 }8 public PageGotoOptions(string url, PageGotoOptionsBase options = null)9 {10 Url = url;11 Options = options;12 }13 public string Url { get; set; }14 public PageGotoOptionsBase Options { get; set; }15 }16}17using Microsoft.Playwright;18using System.Threading.Tasks;19{20 {21 public PageGotoOptionsBase()22 {23 }24 public PageGotoOptionsBase(string url, PageGotoOptionsBase options = null)25 {26 Url = url;27 Options = options;28 }29 public string Url { get; set; }30 public PageGotoOptionsBase Options { get; set; }31 }32}33using Microsoft.Playwright;34using System.Threading.Tasks;35{36 {37 public PageGotoOptionsBase()38 {39 }40 public PageGotoOptionsBase(string url, PageGotoOptionsBase options = null)41 {42 Url = url;43 Options = options;44 }45 public string Url { get; set; }46 public PageGotoOptionsBase Options { get; set; }47 }48}49using Microsoft.Playwright;50using System.Threading.Tasks;51{52 {53 public PageGotoOptionsBase()54 {55 }56 public PageGotoOptionsBase(string url, PageGotoOptionsBase options = null)57 {58 Url = url;59 Options = options;60 }
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!!