Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.SetCookieAsync
SetCookiesTests.cs
Source:SetCookiesTests.cs  
...16        [SkipBrowserFact(skipFirefox: true)]17        public async Task ShouldWork()18        {19            await Page.GoToAsync(TestConstants.EmptyPage);20            await Page.SetCookieAsync(new CookieParam21            {22                Name = "password",23                Value = "123456"24            });25            Assert.Equal("password=123456", await Page.EvaluateExpressionAsync<string>("document.cookie"));26        }27        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should isolate cookies in browser contexts")]28        [SkipBrowserFact(skipFirefox: true)]29        public async Task ShouldIsolateCookiesInBrowserContexts()30        {31            var anotherContext = await Browser.CreateIncognitoBrowserContextAsync();32            var anotherPage = await anotherContext.NewPageAsync();33            await Page.GoToAsync(TestConstants.EmptyPage);34            await anotherPage.GoToAsync(TestConstants.EmptyPage);35            await Page.SetCookieAsync(new CookieParam36            {37                Name = "page1cookie",38                Value = "page1value"39            });40            await anotherPage.SetCookieAsync(new CookieParam41            {42                Name = "page2cookie",43                Value = "page2value"44            });45            var cookies1 = await Page.GetCookiesAsync();46            var cookies2 = await anotherPage.GetCookiesAsync();47            Assert.Single(cookies1);48            Assert.Single(cookies2);49            Assert.Equal("page1cookie", cookies1[0].Name);50            Assert.Equal("page1value", cookies1[0].Value);51            Assert.Equal("page2cookie", cookies2[0].Name);52            Assert.Equal("page2value", cookies2[0].Value);53            await anotherContext.CloseAsync();54        }55        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set multiple cookies")]56        [SkipBrowserFact(skipFirefox: true)]57        public async Task ShouldSetMultipleCookies()58        {59            await Page.GoToAsync(TestConstants.EmptyPage);60            await Page.SetCookieAsync(61                new CookieParam62                {63                    Name = "password",64                    Value = "123456"65                },66                new CookieParam67                {68                    Name = "foo",69                    Value = "bar"70                }71            );72            Assert.Equal(73                new[]74                {75                    "foo=bar",76                    "password=123456"77                },78                await Page.EvaluateFunctionAsync<string[]>(@"() => {79                    const cookies = document.cookie.split(';');80                    return cookies.map(cookie => cookie.trim()).sort();81                }")82            );83        }84        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should have |expires| set to |-1| for session cookies")]85        [PuppeteerFact]86        public async Task ShouldHaveExpiresSetToMinus1ForSessionCookies()87        {88            await Page.GoToAsync(TestConstants.EmptyPage);89            await Page.SetCookieAsync(new CookieParam90            {91                Name = "password",92                Value = "123456"93            });94            var cookies = await Page.GetCookiesAsync();95            Assert.True(cookies[0].Session);96            Assert.Equal(-1, cookies[0].Expires);97        }98        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set cookie with reasonable defaults")]99        [PuppeteerFact]100        public async Task ShouldSetCookieWithReasonableDefaults()101        {102            await Page.GoToAsync(TestConstants.EmptyPage);103            await Page.SetCookieAsync(new CookieParam104            {105                Name = "password",106                Value = "123456"107            });108            var cookie = Assert.Single(await Page.GetCookiesAsync());109            Assert.Equal("password", cookie.Name);110            Assert.Equal("123456", cookie.Value);111            Assert.Equal("localhost", cookie.Domain);112            Assert.Equal("/", cookie.Path);113            Assert.Equal(-1, cookie.Expires);114            Assert.Equal(14, cookie.Size);115            Assert.False(cookie.HttpOnly);116            Assert.False(cookie.Secure);117            Assert.True(cookie.Session);118        }119        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set a cookie with a path")]120        [SkipBrowserFact(skipFirefox: true)]121        public async Task ShouldSetACookieWithAPath()122        {123            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");124            await Page.SetCookieAsync(new CookieParam125            {126                Name = "gridcookie",127                Value = "GRID",128                Path = "/grid.html"129            });130            var cookie = Assert.Single(await Page.GetCookiesAsync());131            Assert.Equal("gridcookie", cookie.Name);132            Assert.Equal("GRID", cookie.Value);133            Assert.Equal("localhost", cookie.Domain);134            Assert.Equal("/grid.html", cookie.Path);135            Assert.Equal(cookie.Expires, -1);136            Assert.Equal(14, cookie.Size);137            Assert.False(cookie.HttpOnly);138            Assert.False(cookie.Secure);139            Assert.True(cookie.Session);140        }141        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should not set a cookie on a blank page")]142        [SkipBrowserFact(skipFirefox: true)]143        public async Task ShouldNotSetACookieOnABlankPage()144        {145            await Page.GoToAsync(TestConstants.AboutBlank);146            var exception = await Assert.ThrowsAsync<MessageException>(async () => await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best" }));147            Assert.Equal("Protocol error (Network.deleteCookies): At least one of the url and domain needs to be specified", exception.Message);148        }149        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should not set a cookie with blank page URL")]150        [PuppeteerFact]151        public async Task ShouldNotSetACookieWithBlankPageURL()152        {153            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");154            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.SetCookieAsync(new CookieParam155            {156                Name = "example-cookie",157                Value = "best"158            }, new CookieParam159            {160                Url = TestConstants.AboutBlank,161                Name = "example-cookie-blank",162                Value = "best"163            }));164            Assert.Equal("Blank page can not have cookie \"example-cookie-blank\"", exception.Message);165        }166        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should not set a cookie on a data URL page")]167        [SkipBrowserFact(skipFirefox: true)]168        public async Task ShouldNotSetACookieOnADataURLPage()169        {170            await Page.GoToAsync("data:,Hello%2C%20World!");171            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best" }));172            Assert.Equal("Protocol error (Network.deleteCookies): At least one of the url and domain needs to be specified", exception.Message);173        }174        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should default to setting secure cookie for HTTPS websites")]175        [SkipBrowserFact(skipFirefox: true)]176        public async Task ShouldDefaultToSettingSecureCookieForHttpsWebsites()177        {178            await Page.GoToAsync(TestConstants.EmptyPage);179            var SecureUrl = "https://example.com";180            await Page.SetCookieAsync(new CookieParam181            {182                Url = SecureUrl,183                Name = "foo",184                Value = "bar"185            });186            var cookie = Assert.Single(await Page.GetCookiesAsync(SecureUrl));187            Assert.True(cookie.Secure);188        }189        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should be able to set unsecure cookie for HTTP website")]190        [SkipBrowserFact(skipFirefox: true)]191        public async Task ShouldBeAbleToSetUnsecureCookieForHttpWebSite()192        {193            await Page.GoToAsync(TestConstants.EmptyPage);194            var SecureUrl = "http://example.com";195            await Page.SetCookieAsync(new CookieParam196            {197                Url = SecureUrl,198                Name = "foo",199                Value = "bar"200            });201            var cookie = Assert.Single(await Page.GetCookiesAsync(SecureUrl));202            Assert.False(cookie.Secure);203        }204        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set a cookie on a different domain")]205        [SkipBrowserFact(skipFirefox: true)]206        public async Task ShouldSetACookieOnADifferentDomain()207        {208            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");209            await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best", Url = "https://www.example.com" });210            Assert.Equal(string.Empty, await Page.EvaluateExpressionAsync<string>("document.cookie"));211            Assert.Empty(await Page.GetCookiesAsync());212            var cookie = Assert.Single(await Page.GetCookiesAsync("https://www.example.com"));213            Assert.Equal("example-cookie", cookie.Name);214            Assert.Equal("best", cookie.Value);215            Assert.Equal("www.example.com", cookie.Domain);216            Assert.Equal("/", cookie.Path);217            Assert.Equal(cookie.Expires, -1);218            Assert.Equal(18, cookie.Size);219            Assert.False(cookie.HttpOnly);220            Assert.True(cookie.Secure);221            Assert.True(cookie.Session);222        }223        [PuppeteerTest("cookies.spec.ts", "Page.setCookie", "should set cookies from a frame")]224        [SkipBrowserFact(skipFirefox: true)]225        public async Task ShouldSetCookiesFromAFrame()226        {227            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");228            await Page.SetCookieAsync(new CookieParam { Name = "localhost-cookie", Value = "best" });229            await Page.EvaluateFunctionAsync(@"src => {230                    let fulfill;231                    const promise = new Promise(x => fulfill = x);232                    const iframe = document.createElement('iframe');233                    document.body.appendChild(iframe);234                    iframe.onload = fulfill;235                    iframe.src = src;236                    return promise;237                }", TestConstants.CrossProcessHttpPrefix);238            await Page.SetCookieAsync(new CookieParam { Name = "127-cookie", Value = "worst", Url = TestConstants.CrossProcessHttpPrefix });239            Assert.Equal("localhost-cookie=best", await Page.EvaluateExpressionAsync<string>("document.cookie"));240            Assert.Equal(string.Empty, await Page.FirstChildFrame().EvaluateExpressionAsync<string>("document.cookie"));241            var cookie = Assert.Single(await Page.GetCookiesAsync());242            Assert.Equal("localhost-cookie", cookie.Name);243            Assert.Equal("best", cookie.Value);244            Assert.Equal("localhost", cookie.Domain);245            Assert.Equal("/", cookie.Path);246            Assert.Equal(cookie.Expires, -1);247            Assert.Equal(20, cookie.Size);248            Assert.False(cookie.HttpOnly);249            Assert.False(cookie.Secure);250            Assert.True(cookie.Session);251            cookie = Assert.Single(await Page.GetCookiesAsync(TestConstants.CrossProcessHttpPrefix));252            Assert.Equal("127-cookie", cookie.Name);...BrowserUtils.cs
Source:BrowserUtils.cs  
...82                    };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                    };163                    string originalUserAgent = await browser.GetUserAgentAsync();164                    await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}");165                    if (cookies.Any()) {166                        await page.SetCookieAsync(cookies.ToArray());167                    }168                    await page.GoToAsync(url, navigationOptions);169                    return await page.ScreenshotDataAsync(options);170                } finally {171                    await Cleanup(page);172                }173            } finally {174                Cleanup(browser);175            }176        }177        public bool UserAgentMatches(string userAgent) {178            return userAgent.EndsWith($" {USER_AGENT_SUFFIX}");179        }180        private async Task Cleanup(Page page) {...CookiesTests.cs
Source:CookiesTests.cs  
...26            Assert.Equal(16, cookie.Size);27            Assert.False(cookie.HttpOnly);28            Assert.False(cookie.Secure);29            Assert.True(cookie.Session);30            await Page.SetCookieAsync(new CookieParam31            {32                Name = "password",33                Value = "123456"34            });35            Assert.Equal("username=John Doe; password=123456", await Page.EvaluateExpressionAsync<string>("document.cookie"));36            var cookies = (await Page.GetCookiesAsync()).OrderBy(c => c.Name).ToList();37            Assert.Equal(2, cookies.Count);38            Assert.Equal("password", cookies[0].Name);39            Assert.Equal("123456", cookies[0].Value);40            Assert.Equal("localhost", cookies[0].Domain);41            Assert.Equal("/", cookies[0].Path);42            Assert.Equal(cookies[0].Expires, -1);43            Assert.Equal(14, cookies[0].Size);44            Assert.False(cookies[0].HttpOnly);45            Assert.False(cookies[0].Secure);46            Assert.True(cookies[0].Session);47            Assert.Equal("username", cookies[1].Name);48            Assert.Equal("John Doe", cookies[1].Value);49            Assert.Equal("localhost", cookies[1].Domain);50            Assert.Equal("/", cookies[1].Path);51            Assert.Equal(cookies[1].Expires, -1);52            Assert.Equal(16, cookies[1].Size);53            Assert.False(cookies[1].HttpOnly);54            Assert.False(cookies[1].Secure);55            Assert.True(cookies[1].Session);56        }57        [Fact]58        public async Task ShouldSetACookieWithAPath()59        {60            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");61            await Page.SetCookieAsync(new CookieParam62            {63                Name = "gridcookie",64                Value = "GRID",65                Path = "/grid.html"66            });67            var cookie = Assert.Single(await Page.GetCookiesAsync());68            Assert.Equal("gridcookie", cookie.Name);69            Assert.Equal("GRID", cookie.Value);70            Assert.Equal("localhost", cookie.Domain);71            Assert.Equal("/grid.html", cookie.Path);72            Assert.Equal(cookie.Expires, -1);73            Assert.Equal(14, cookie.Size);74            Assert.False(cookie.HttpOnly);75            Assert.False(cookie.Secure);76            Assert.True(cookie.Session);77            Assert.Equal("gridcookie=GRID", await Page.EvaluateExpressionAsync<string>("document.cookie"));78            await Page.GoToAsync(TestConstants.ServerUrl + "/empty.html");79            Assert.Empty(await Page.GetCookiesAsync());80            Assert.Equal(string.Empty, await Page.EvaluateExpressionAsync<string>("document.cookie"));81            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");82            Assert.Equal("gridcookie=GRID", await Page.EvaluateExpressionAsync<string>("document.cookie"));83        }84        [Fact]85        public async Task ShouldDeleteACookie()86        {87            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");88            await Page.SetCookieAsync(new CookieParam89            {90                Name = "cookie1",91                Value = "1"92            }, new CookieParam93            {94                Name = "cookie2",95                Value = "2"96            }, new CookieParam97            {98                Name = "cookie3",99                Value = "3"100            });101            Assert.Equal("cookie1=1; cookie2=2; cookie3=3", await Page.EvaluateExpressionAsync<string>("document.cookie"));102            await Page.DeleteCookieAsync(new CookieParam { Name = "cookie2" });103            Assert.Equal("cookie1=1; cookie3=3", await Page.EvaluateExpressionAsync<string>("document.cookie"));104        }105        [Fact]106        public async Task ShouldNotSetACookieOnABlankPage()107        {108            await Page.GoToAsync(TestConstants.AboutBlank);109            var exception = await Assert.ThrowsAsync<MessageException>(async () => await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best" }));110            Assert.Equal("Protocol error (Network.deleteCookies): At least one of the url and domain needs to be specified ", exception.Message);111        }112        [Fact]113        public async Task ShouldNotSetACookieWithBlankPageURL()114        {115            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");116            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.SetCookieAsync(new CookieParam117            {118                Name = "example-cookie",119                Value = "best"120            }, new CookieParam121            {122                Url = TestConstants.AboutBlank,123                Name = "example-cookie-blank",124                Value = "best"125            }));126            Assert.Equal("Blank page can not have cookie \"example-cookie-blank\"", exception.Message);127        }128        [Fact]129        public async Task ShouldNotSetACookieOnADataURLPage()130        {131            await Page.GoToAsync("data:,Hello%2C%20World!");132            var exception = await Assert.ThrowsAnyAsync<Exception>(async () => await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best" }));133            Assert.Equal("Protocol error (Network.deleteCookies): At least one of the url and domain needs to be specified ", exception.Message);134        }135        [Fact]136        public async Task ShouldSetACookieOnADifferentDomain()137        {138            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");139            await Page.SetCookieAsync(new CookieParam { Name = "example-cookie", Value = "best", Url = "https://www.example.com" });140            Assert.Equal(string.Empty, await Page.EvaluateExpressionAsync<string>("document.cookie"));141            Assert.Empty(await Page.GetCookiesAsync());142            var cookie = Assert.Single(await Page.GetCookiesAsync("https://www.example.com"));143            Assert.Equal("example-cookie", cookie.Name);144            Assert.Equal("best", cookie.Value);145            Assert.Equal("www.example.com", cookie.Domain);146            Assert.Equal("/", cookie.Path);147            Assert.Equal(cookie.Expires, -1);148            Assert.Equal(18, cookie.Size);149            Assert.False(cookie.HttpOnly);150            Assert.True(cookie.Secure);151            Assert.True(cookie.Session);152        }153        [Fact]154        public async Task ShouldSetCookiesFromAFrame()155        {156            await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");157            await Page.SetCookieAsync(new CookieParam { Name = "localhost-cookie", Value = "best" });158            await Page.EvaluateFunctionAsync(@"src => {159                    let fulfill;160                    const promise = new Promise(x => fulfill = x);161                    const iframe = document.createElement('iframe');162                    document.body.appendChild(iframe);163                    iframe.onload = fulfill;164                    iframe.src = src;165                    return promise;166                }", TestConstants.CrossProcessHttpPrefix);167            await Page.SetCookieAsync(new CookieParam { Name = "127-cookie", Value = "worst", Url = TestConstants.CrossProcessHttpPrefix });168            Assert.Equal("localhost-cookie=best", await Page.EvaluateExpressionAsync<string>("document.cookie"));169            Assert.Equal("127-cookie=worst", await Page.Frames.ElementAt(1).EvaluateExpressionAsync<string>("document.cookie"));170            var cookie = Assert.Single(await Page.GetCookiesAsync());171            Assert.Equal("localhost-cookie", cookie.Name);172            Assert.Equal("best", cookie.Value);173            Assert.Equal("localhost", cookie.Domain);174            Assert.Equal("/", cookie.Path);175            Assert.Equal(cookie.Expires, -1);176            Assert.Equal(20, cookie.Size);177            Assert.False(cookie.HttpOnly);178            Assert.False(cookie.Secure);179            Assert.True(cookie.Session);180            cookie = Assert.Single(await Page.GetCookiesAsync(TestConstants.CrossProcessHttpPrefix));181            Assert.Equal("127-cookie", cookie.Name);...WorkerActivities.cs
Source:WorkerActivities.cs  
...51            var type = searchargs[1];52            var cookies = CookieConverter.DecodeCookie(arguments.Item2);53            var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });54            var page = await browser.NewPageAsync();55            await page.SetCookieAsync(cookies);56            var search = new UIAction.NavigateSearch(query, type);57            var pages = await search.RunAsync(page);58            browser.Disconnect();59            return pages;60        }61        // O) Accept search query and cookies and page and configsection then return result62        [FunctionName("RetrievePageContent")]63        public static async Task<WorkerResult> RetrievePageContent(64                [ActivityTrigger] DurableActivityContext ctx,65                TraceWriter log)66        {67            var arguments = ctx.GetInput<Tuple<string, string, int, string>>();68            var searchargs = arguments.Item1.Split(':');69            if (searchargs.Length != 2)70            {71                throw new ArgumentException("Activity.QueryGuru: Expected search query to be in format <query>:<type>");72            }73            var query = searchargs[0];74            var type = searchargs[1];75            var cookies = CookieConverter.DecodeCookie(arguments.Item2);76            var pagenumber = arguments.Item3;77            var config = JsonConvert.DeserializeObject<ConfigSection>(arguments.Item4);78            var browser = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserWSEndpoint = Constants.BrowserWSEndpoint });79            var page = await browser.NewPageAsync();80            await page.SetCookieAsync(cookies);81            var search = new UIAction.NavigateSearch(query, type, true);82            await search.RunAsync(page);83            var collect = new UIAction.NavigateCollect(pagenumber, ctx.InstanceId, ctx.InstanceId, config);84            var result = await collect.RunAsync(page);85            // page is closed implicitly86            browser.Disconnect();87            var customresult = new WorkerResult { html = result, page = pagenumber };88            return customresult;89        }90        // A) Accept number of pages and return a range from 1 to number of pages91        [FunctionName("CreateWorkload")]92        public static async Task<List<int>> CreateWorkload(93                [ActivityTrigger] DurableActivityContext ctx,94                TraceWriter log)...PupeteerExtensions.cs
Source:PupeteerExtensions.cs  
...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);66            await page.PressControlPaste();...GetPage.cs
Source:GetPage.cs  
...56                    await page.SetExtraHttpHeadersAsync(dic);57                    await page.SetUserAgentAsync("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36");58                    59                    var response = await page.GoToAsync("https://www.bet365.com/#/AVR/B24/R^1/", navigation);60                    //await page.SetCookieAsync(await page.GetCookiesAsync());61                    if (!response.Ok)62                        return false;63                }64                return await NavigateToResultsDiv();65            }66            catch67            {68                return false;69            }70        }71        private static async Task<bool> NavigateToResultsDiv()72        {73            Login login = new();74            try...PageFactory.cs
Source:PageFactory.cs  
...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"}});31    }32}...Program.cs
Source:Program.cs  
...10while (true)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}...SetCookieAsync
Using AI Code Generation
1using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3}))4{5    var page = await browser.NewPageAsync();6    await page.SetCookieAsync(new CookieParam7    {8    });9    var cookies = await page.GetCookiesAsync();10    foreach (var cookie in cookies)11    {12        Console.WriteLine(cookie.Name + ";" + cookie.Value);13    }14}15using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions16{17}))18{19    var page = await browser.NewPageAsync();20    await page.SetCookieAsync(new CookieParam21    {22    });23    var cookies = await page.GetCookiesAsync();24    foreach (var cookie in cookies)25    {26        Console.WriteLine(cookie.Name + ";" + cookie.Value);27    }28}29using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions30{31}))32{33    var page = await browser.NewPageAsync();34    await page.SetCookieAsync(new CookieParam35    {36    });37    var cookies = await page.GetCookiesAsync();38    foreach (var cookie in cookies)39    {40        Console.WriteLine(cookie.Name + ";" + cookie.Value);41    }42}43using (var browser = await Puppeteer.LaunchAsync(newSetCookieAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });10            var page = await browser.NewPageAsync();11            await page.SetCookieAsync(new CookieParam12            {13                Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()14            });15            await page.SetCookieAsync(new CookieParam16            {17                Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()18            });19            await page.SetCookieAsync(new CookieParam20            {21                Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()22            });23            await browser.CloseAsync();24        }25    }26}27using System;28using System.Threading.Tasks;29using PuppeteerSharp;30{31    {32        static async Task Main(string[] args)33        {34            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);35            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });36            var page = await browser.NewPageAsync();37            await page.SetCookieAsync(new CookieParam38            {39                Expires = DateTime.Now.AddDays(1).ToUnixTimeSeconds()40            });41            await page.SetCookieAsync(new CookieParam42            {SetCookieAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.SetCookieAsync(new CookieParam3{4});5var page = await browser.NewPageAsync();6await page.SetCookieAsync(new CookieParam7{8});9const puppeteer = require('puppeteer');10(async () => {11    const browser = await puppeteer.launch();12    const page = await browser.newPage();13    const cookies = await page.cookies();14    console.log(cookies);15    await browser.close();16})();17  {18  }19const puppeteer = require('puppeteer');20(async () => {21    const browser = await puppeteer.launch();SetCookieAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions10            {11            }))12            using (var page = await browser.NewPageAsync())13            {14                await page.SetCookieAsync(new CookieParam15                {16                });17            }18        }19    }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25    {26        static async Task Main(string[] args)27        {28            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);29            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions30            {31            }))32            using (varSetCookieAsync
Using AI Code Generation
1await page.SetCookieAsync(new CookieParam2{3});4await page.SetCookieAsync(new CookieParam5{6});7await page.SetCookieAsync(new CookieParam8{9});10await page.SetCookieAsync(new CookieParam11{12});13await page.SetCookieAsync(new CookieParam14{15});16await page.SetCookieAsync(new CookieParam17{18});19await page.SetCookieAsync(new CookieParam20{21});22await page.SetCookieAsync(new CookieParam23{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!!
