Best Puppeteer-sharp code snippet using PuppeteerSharp.CookieParam
BrowserUtils.cs
Source:BrowserUtils.cs
...62 if (Directory.Exists(revision.FolderPath) && !IsValidRevision(revision)) {63 throw new InvalidDataException("Could not find browser in " + revision.ExecutablePath);64 }65 }66 public async Task<byte[]> PrintPDF(string url, IEnumerable<CookieParam> cookies, ViewPortOptions viewport, PdfOptions options, RevisionInfo revision) {67 LaunchOptions launchOptions = new LaunchOptions() {68 ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",69 Args = BrowserArgs,70 Headless = true,71 DefaultViewport = viewport,72 Timeout = 073 };74 browser = await Puppeteer.LaunchAsync(launchOptions);75 try {76 var page = await browser.NewPageAsync();77 try {78 WaitUntilNavigation[] waitUntilNavigations = { WaitUntilNavigation.Networkidle0 };79 NavigationOptions navigationOptions = new NavigationOptions() {80 Timeout = 0,81 WaitUntil = waitUntilNavigations82 };83 string originalUserAgent = await browser.GetUserAgentAsync();84 await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}");85 if (cookies.Any()) {86 await page.SetCookieAsync(cookies.ToArray());87 }88 await page.GoToAsync(url, navigationOptions);89 await InjectCustomStylesAsync(page, ref options);90 91 bool hasPageNumbers = await page.EvaluateFunctionAsync<bool>("(window.UltimatePDF? window.UltimatePDF.hasPageNumbers : function() { return false; })");92 if (hasPageNumbers) {93 /*94 * When the layout has page numbers, we first retrieve a95 * first blank pdf to calculate the number of pages.96 * Then, knowing how many pages, we can layout the headers and footers,97 * and retrieve the final pdf.98 */99 byte[] blankContents = await page.PdfDataAsync(options);100 using (var blankPdf = new PDFUtils(blankContents)) {101 await page.EvaluateFunctionAsync("window.UltimatePDF.layoutPages", blankPdf.Pages);102 return await page.PdfDataAsync(options);103 }104 } else {105 return await page.PdfDataAsync(options);106 }107 } finally {108 await Cleanup(page);109 }110 } finally {111 Cleanup(browser);112 }113 }114 private Task InjectCustomStylesAsync(Page page, ref PdfOptions options) {115 /*116 * It seems that Puppeteer is not overriding the page styles from the print stylesheet.117 * As a workaround, we inject a <style> tag with the @page overrides at the end of <head>.118 * This issue might be eventually resolved in Puppeteer, and seems to be tracked by https://github.com/GoogleChrome/puppeteer/issues/393119 */120 string overrides = string.Empty;121 if (!options.PreferCSSPageSize && options.Width != null && options.Height != null) {122 overrides += $"size: {options.Width} {options.Height}; ";123 }124 if (options.MarginOptions.Top != null) {125 overrides += $"margin-top: {options.MarginOptions.Top}; ";126 }127 if (options.MarginOptions.Right != null) {128 overrides += $"margin-right: {options.MarginOptions.Right}; ";129 }130 if (options.MarginOptions.Bottom != null) {131 overrides += $"margin-bottom: {options.MarginOptions.Bottom}; ";132 }133 if (options.MarginOptions.Left != null) {134 overrides += $"margin-left: {options.MarginOptions.Left}; ";135 }136 if (!string.IsNullOrEmpty(overrides)) {137 /* Change the options so that Puppeteer respects our overrides */138 options.PreferCSSPageSize = true;139 options.Width = options.Height = null;140 options.MarginOptions = new MarginOptions();141 /* We must add the <style> tag at the end of <body> to make sure it is not overriden */142 string pageOverrides = "@page { " + overrides + "}";143 return page.EvaluateExpressionAsync($"const style = document.createElement('style'); style.innerHTML = '{pageOverrides}'; document.head.appendChild(style);");144 } else {145 return Task.CompletedTask;146 }147 }148 public async Task<byte[]> ScreenshotPNG(string url, IEnumerable<CookieParam> cookies, ViewPortOptions viewport, ScreenshotOptions options, RevisionInfo revision) {149 LaunchOptions launchOptions = new LaunchOptions() {150 ExecutablePath = revision.ExecutablePath,151 Args = BrowserArgs,152 Headless = true,153 DefaultViewport = viewport,154 Timeout = 0155 };156 browser = await Puppeteer.LaunchAsync(launchOptions);157 try {158 var page = await browser.NewPageAsync();159 try {160 NavigationOptions navigationOptions = new NavigationOptions() {161 Timeout = 0162 };...
PupeteerExtensions.cs
Source:PupeteerExtensions.cs
...39 {40 // This gets all cookies from all URLs, not just the current URL41 var client = await page.Target.CreateCDPSessionAsync();42 var cookiesJToken = (await client.SendAsync("Network.getAllCookies"))["cookies"];43 var cookiesDynamic = ((JArray)cookiesJToken).ToObject<CookieParam[]>();44 await File.WriteAllTextAsync(cookiesPath, JsonConvert.SerializeObject(cookiesDynamic));45 }46 public static async Task RestoreCookiesAsync(this Page page, string cookiesPath) 47 {48 try 49 {50 var cookiesJson = await File.ReadAllTextAsync(cookiesPath);51 var cookies = JsonConvert.DeserializeObject<CookieParam[]>(cookiesJson);52 await page.SetCookieAsync(cookies);53 } 54 catch (Exception err) 55 {56 WriteOnConsole("Restore cookie error" + err.Message);57 }58 }59 public static async Task PasteOnElementAsync(this Page page, string elementSelector, string text)60 {61 var temp = await ClipboardService.GetTextAsync();62 var pieces = text.Split(new string[] { "\r\n", "\n\r" }, StringSplitOptions.None).ToList();63 var message = String.Join('\n', pieces);64 await ClipboardService.SetTextAsync(message);65 await page.FocusAsync(elementSelector);...
NavigateLogin.cs
Source:NavigateLogin.cs
...6 using System.Text;7 using System.Threading.Tasks;8 using Microsoft.Azure.WebJobs.Host;9 using PuppeteerSharp;10 public class Login : UIAction.UIActionBase<CookieParam[]>11 {12 private string Username = "";13 private string Pasword = "";14 private string loginurl = "https://www.property-guru.co.nz/gurux/";15 private ElementHandle elusername;16 private ElementHandle elpassword;17 private ElementHandle elbutton;18 public CookieParam[] cookies { get; set; }19 Page Page = null;20 public Login()21 {22 this.Username = "jared.cooksley@raywhite.com";23 this.Pasword = "Jared2017";24 }25 public Login(string username, string password)26 {27 this.Username = username;28 this.Pasword = password;29 }30 public override async Task<CookieParam[]> RunAsync(Page page)31 {32 this.SetPageAsync(page);33 await this.InitialiseAsync();34 await this.ProcessAsync();35 await this.Commit();36 return this.cookies;37 }38 public async Task<CookieParam[]> RunAsync(Page page, TraceWriter log)39 {40 this.log = log;41 this.SetPageAsync(page);42 await this.InitialiseAsync();43 await this.ProcessAsync();44 await this.Commit();45 return this.cookies;46 }47 private async void SetPageAsync(Page page)48 {49 this.Page = page;50 //this.Page.Request += this.DenyRequests;51 //await this.Page.SetRequestInterceptionAsync(false);52 }...
DefaultBrowserContextTests.cs
Source:DefaultBrowserContextTests.cs
...39 [PuppeteerFact]40 public async Task PageSetCookiesAsyncShouldWork()41 {42 await Page.GoToAsync(TestConstants.EmptyPage);43 await Page.SetCookieAsync(new CookieParam44 {45 Name = "username",46 Value = "John Doe"47 });48 var cookie = (await Page.GetCookiesAsync()).First();49 Assert.Equal("username", cookie.Name);50 Assert.Equal("John Doe", cookie.Value);51 Assert.Equal("localhost", cookie.Domain);52 Assert.Equal("/", cookie.Path);53 Assert.Equal(-1, cookie.Expires);54 Assert.Equal(16, cookie.Size);55 Assert.False(cookie.HttpOnly);56 Assert.False(cookie.Secure);57 Assert.True(cookie.Session);58 }59 [PuppeteerTest("defaultbrowsercontext.spec.ts", "DefaultBrowserContext", "page.deleteCookie() should work")]60 [PuppeteerFact]61 public async Task PageDeleteCookieAsyncShouldWork()62 {63 await Page.GoToAsync(TestConstants.EmptyPage);64 await Page.SetCookieAsync(65 new CookieParam66 {67 Name = "cookie1",68 Value = "1"69 },70 new CookieParam71 {72 Name = "cookie2",73 Value = "2"74 });75 Assert.Equal("cookie1=1; cookie2=2", await Page.EvaluateExpressionAsync<string>("document.cookie"));76 await Page.DeleteCookieAsync(new CookieParam77 {78 Name = "cookie2"79 });80 Assert.Equal("cookie1=1", await Page.EvaluateExpressionAsync<string>("document.cookie"));81 var cookie = (await Page.GetCookiesAsync()).First();82 Assert.Equal("cookie1", cookie.Name);83 Assert.Equal("1", cookie.Value);84 Assert.Equal("localhost", cookie.Domain);85 Assert.Equal("/", cookie.Path);86 Assert.Equal(-1, cookie.Expires);87 Assert.Equal(8, cookie.Size);88 Assert.False(cookie.HttpOnly);89 Assert.False(cookie.Secure);90 Assert.True(cookie.Session);...
AuthService.cs
Source:AuthService.cs
...9namespace BetterTravel.Services10{11 public interface IAuthService12 {13 Task<CookieParam[]> AuthenticateAsync(string username, string password, int timeout);14 }15 public class AuthService : IAuthService, IDisposable16 {17 private readonly ILogger _logger;18 private readonly Browser _browser;19 public AuthService() => 20 (_logger, _browser) = (Log.ForContext<AuthService>(), InitBrowser());21 public async Task<CookieParam[]> AuthenticateAsync(string username, string password, int timeout)22 {23 _logger.Information(24 "Try to authenticate...", username, new string(password.Select(t => '*').ToArray()));25 26 var page = await _browser.NewPageAsync();27 await page.GoToAsync("https://www.instagram.com/accounts/login/");28 await page.WaitForTimeoutAsync(timeout);29 await page.WaitForSelectorAsync(Consts.UserNameSelector);30 await page.FocusAsync(Consts.UserNameSelector);31 await page.Keyboard.TypeAsync(InstagramConfiguration.Username);32 await page.WaitForSelectorAsync(Consts.PasswordSelector);33 await page.FocusAsync(Consts.PasswordSelector);34 await page.Keyboard.TypeAsync(InstagramConfiguration.Password);35 await page.WaitForSelectorAsync(Consts.SubmitBtnSelector);...
DeleteCookiesTests.cs
Source:DeleteCookiesTests.cs
...15 [SkipBrowserFact(skipFirefox: true)]16 public async Task ShouldWork()17 {18 await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");19 await Page.SetCookieAsync(new CookieParam20 {21 Name = "cookie1",22 Value = "1"23 }, new CookieParam24 {25 Name = "cookie2",26 Value = "2"27 }, new CookieParam28 {29 Name = "cookie3",30 Value = "3"31 });32 Assert.Equal("cookie1=1; cookie2=2; cookie3=3", await Page.EvaluateExpressionAsync<string>("document.cookie"));33 await Page.DeleteCookieAsync(new CookieParam { Name = "cookie2" });34 Assert.Equal("cookie1=1; cookie3=3", await Page.EvaluateExpressionAsync<string>("document.cookie"));35 }36 }37}...
PageFactory.cs
Source:PageFactory.cs
...11 12 public class BrowserPageFactory : IBrowserPageFactory13 {14 private readonly ILogger _logger;15 private readonly CookieParam[] _cookies;16 public BrowserPageFactory(CookieParam[] cookies) => 17 (_logger, _cookies) = (Log.ForContext<BrowserPageFactory>(), cookies);18 public async Task<Page> ConcretePageAsync(bool withCookies)19 {20 var browser = await InitBrowserAsync();21 var page = await browser.NewPageAsync();22 if (withCookies)23 await page.SetCookieAsync(_cookies);24 25 _logger.Information($"Created new browser. Cookies: {withCookies.ToString()}", page.Url);26 return page;27 }28 29 private static async Task<Browser> InitBrowserAsync() => 30 await Puppeteer.LaunchAsync(new LaunchOptions {Headless = true, Args = new []{"--no-sandbox"}});...
Program.cs
Source:Program.cs
...11{12 using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });13 using var page = await browser.NewPageAsync();14 await page.SetCookieAsync(15 new CookieParam { Name = "__client_id", Value = cid, Domain = "www.luogu.com.cn" },16 new CookieParam { Name = "_uid", Value = uid, Domain = "www.luogu.com.cn" });17 page.DefaultNavigationTimeout = 250000;18 page.DefaultTimeout = 250000;19 await page.GoToAsync("https://www.luogu.com.cn/");20 await (await page.QuerySelectorAsync("a[title='hello']")).ClickAsync();21 Thread.Sleep(10000);22 await browser.CloseAsync();23 Thread.Sleep(86400000 - 10000);24}...
CookieParam
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 public string Name { get; set; }7 public string Value { get; set; }8 public string Url { get; set; }9 public string Domain { get; set; }10 public string Path { get; set; }11 public DateTime? Expires { get; set; }12 public bool? HttpOnly { get; set; }13 public bool? Secure { get; set; }14 public string SameSite { get; set; }15 }16}17using PuppeteerSharp;18using System;19using System.Threading.Tasks;20{21 {22 public string Name { get; set; }23 public string Value { get; set; }24 public string Url { get; set; }25 public string Domain { get; set; }26 public string Path { get; set; }27 public DateTime? Expires { get; set; }28 public bool? HttpOnly { get; set; }29 public bool? Secure { get; set; }30 public string SameSite { get; set; }31 }32}33using PuppeteerSharp;34using System;35using System.Threading.Tasks;36{37 {38 public string Name { get; set; }39 public string Value { get; set; }40 public string Url { get; set; }41 public string Domain { get; set; }42 public string Path { get; set; }43 public DateTime? Expires { get; set; }44 public bool? HttpOnly { get; set; }45 public bool? Secure { get; set; }46 public string SameSite { get; set; }47 }48}49using PuppeteerSharp;
CookieParam
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 await page.WaitForTimeoutAsync(2000);16 var cookie = await page.GetCookiesAsync();17 foreach (var item in cookie)18 {19 Console.WriteLine(item.Name + " : " + item.Value);20 }21 }22 }23 }24 }25}
CookieParam
Using AI Code Generation
1var puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8var puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();15var puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.screenshot({path: 'example.png'});20 await browser.close();21})();22var puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const page = await browser.newPage();26 await page.screenshot({path: 'example.png'});27 await browser.close();28})();29var puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const page = await browser.newPage();33 await page.screenshot({path: 'example.png'});34 await browser.close();35})();36var puppeteer = require('puppeteer');37(async () => {38 const browser = await puppeteer.launch();39 const page = await browser.newPage();40 await page.screenshot({path: 'example.png'});41 await browser.close();42})();43var puppeteer = require('
CookieParam
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using PuppeteerSharp;7{8 {9 public string name { get; set; }10 public string value { get; set; }11 public string url { get; set; }12 public string domain { get; set; }13 public string path { get; set; }14 public int? expires { get; set; }15 public bool? httpOnly { get; set; }16 public bool? secure { get; set; }17 public bool? session { get; set; }18 }19}20using System;21using System.Collections.Generic;22using System.Linq;23using System.Text;24using System.Threading.Tasks;25using PuppeteerSharp;26using PuppeteerSharp.Helpers;27using PuppeteerSharp.Input;28using PuppeteerSharp.Messaging;
CookieParam
Using AI Code Generation
1{2};3await page.SetCookieAsync(cookieParam);4{5};6await page.SetCookieAsync(cookie);7{8};9await page.SetCookieAsync(cookieParam);10{11};12await page.SetCookieAsync(cookie);13{14};15await page.SetCookieAsync(cookieParam);16{17};18await page.SetCookieAsync(cookie);
CookieParam
Using AI Code Generation
1CookieParam cookieParam = new CookieParam();2cookieParam.Name = "cookieName";3cookieParam.Value = "cookieValue";4cookieParam.Domain = "domain";5cookieParam.Path = "path";6cookieParam.Expires = "expires";7cookieParam.HttpOnly = "httpOnly";8cookieParam.Secure = "secure";9await page.SetCookieAsync(cookieParam);10CookieParam cookieParam = await page.GetCookieAsync("cookieName");11await page.DeleteCookieAsync("cookieName");12CookieParam[] cookieParams = await page.GetCookiesAsync();13await page.ClearCookiesAsync();14string[] cookieNames = await page.GetCookieNamesAsync();15string cookies = await page.GetCookiesAsStringsAsync();16await page.SetCookiesAsStringsAsync("cookie1=cookie1Value;cookie2=cookie2Value");17string cookies = await page.GetCookiesAsStringsAsync();18await page.SetCookiesAsStringsAsync("cookie1=cookie1Value;cookie2=cookie2Value");19string cookies = await page.GetCookiesAsStringsAsync();20await page.SetCookiesAsStringsAsync("cookie1=cookie1Value;cookie2=cookie2Value");21string cookies = await page.GetCookiesAsStringsAsync();22await page.SetCookiesAsStringsAsync("cookie1=cookie1Value;cookie2=cookie2Value");23string cookies = await page.GetCookiesAsStringsAsync();24await page.SetCookiesAsStringsAsync("cookie1=cookie1Value;cookie2=cookie2Value");25string cookies = await page.GetCookiesAsStringsAsync();26await page.SetCookiesAsStringsAsync("cookie1=cookie1Value;cookie2=cookie2Value");27string cookies = await page.GetCookiesAsStringsAsync();
CookieParam
Using AI Code Generation
1{2 Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()3};4await page.SetCookieAsync(cookieParam);5{6 Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()7};8await page.SetCookieAsync(cookieParam);9{10 Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()11};12await page.SetCookieAsync(cookieParam);13{14 Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()15};16await page.SetCookieAsync(cookieParam);17{18 Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()19};20await page.SetCookieAsync(cookieParam);21{22 Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()23};24await page.SetCookieAsync(cookieParam);25{
CookieParam
Using AI Code Generation
1var cookie = new CookieParam()2{3 Expires = DateTime.Now.AddYears(1).ToUnixTimestamp()4};5await page.SetCookieAsync(cookie);6var cookie = new CookieParam()7{8 Expires = DateTime.Now.AddYears(1).ToUnixTimestamp(),9};10await page.SetCookieAsync(cookie);11var cookie = new CookieParam()12{13 Expires = DateTime.Now.AddYears(1).ToUnixTimestamp(),14};15await page.SetCookieAsync(cookie);16var cookie = new CookieParam()17{18 Expires = DateTime.Now.AddYears(1).ToUnixTimestamp(),19};20await page.SetCookieAsync(cookie);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!