Best Puppeteer-sharp code snippet using PuppeteerSharp.Target.CreateCDPSessionAsync
CDPSession.cs
Source:CDPSession.cs
...15 /// Documentation on DevTools Protocol can be found here: <see href="https://chromedevtools.github.io/devtools-protocol/"/>.16 ///17 /// <code>18 /// <![CDATA[19 /// var client = await Page.Target.CreateCDPSessionAsync();20 /// await client.SendAsync("Animation.enable");21 /// client.MessageReceived += (sender, e) =>22 /// {23 /// if (e.MessageID == "Animation.animationCreated")24 /// {25 /// Console.WriteLine("Animation created!");26 /// }27 /// };28 /// JObject response = await client.SendAsync("Animation.getPlaybackRate");29 /// Console.WriteLine("playback rate is " + response.playbackRate);30 /// await client.SendAsync("Animation.setPlaybackRate", new31 /// {32 /// playbackRate = Convert.ToInt32(response.playbackRate / 2)33 /// });...
Scrape.cs
Source:Scrape.cs
...53 await page.Tracing.StartAsync(new TracingOptions54 {55 Categories = new List<string> { "devtools.timeline" }56 });57 var client = await page.Target.CreateCDPSessionAsync();58 await client.SendAsync("Network.clearBrowserCache");59 await page.GoToAsync(url, timeout: 0);60 string rawTrace = await page.Tracing.StopAsync();61 string content = await page.GetContentAsync();62 //Image63 var imageElements = await page.QuerySelectorAllAsync("img");64 if (imageElements != null)65 {66 imageCount = imageElements.Count();67 imageProperties = await new ImageHelper().GetImageData(imageElements);68 }69 await browser.CloseAsync();70 //Trace71 traces = new TraceHelper().GetTraceData(rawTrace);...
WinamaxEventScraper.cs
Source:WinamaxEventScraper.cs
...26 _platformEvent = platformEvent;27 }28 public async Task SubscribeToLive(Action<LiveOddsUpdate> callback)29 {30 var client = await Page.Target.CreateCDPSessionAsync();31 await client.SendAsync("Network.enable");32 await client.SendAsync("Page.enable");33 client.MessageReceived += (sender, e) =>34 {35 if (e.MessageID == "Network.webSocketFrameReceived")36 {37 var payloadData = e.MessageData["response"]["payloadData"].ToString();38 if (TryParseOdds(payloadData, out var odds))39 callback.Invoke(odds);40 }41 };42 //await _page.GoToAsync($"https://www.winamax.fr/paris-sportifs/match/live/{_event}");43 }44 public async Task<OutcomesSnapshot> ScrapPage()...
BrowserContextManager.cs
Source:BrowserContextManager.cs
...21 public BrowserContextManager(Browser browser)22 {23 context = NewContext(browser).GetAwaiter().GetResult();24 whatsapp = NewWhatsappPage(context).GetAwaiter().GetResult();25 var devTools = whatsapp.Target.CreateCDPSessionAsync().GetAwaiter().GetResult();26 devTools.SendAsync("Network.enable").GetAwaiter().GetResult();27 }28 public BrowserContextManager(Browser browser, PageState state) : this(browser)29 {30 state.RestoreState(whatsapp).GetAwaiter().GetResult();31 }32 private async Task<BrowserContext> NewContext(Browser browser)33 => await browser.CreateIncognitoBrowserContextAsync();34 private async Task<Page> NewWhatsappPage(BrowserContext context)35 {36 var page = await context.NewPageAsync();37 await page.SetUserAgentAsync(USER_AGENT);38 await page.SetViewportAsync(VIEW_PORT);39 await page.GoToAsync("https://web.whatsapp.com/");...
PupeteerExtensions.cs
Source:PupeteerExtensions.cs
...37 }38 public static async Task SaveCookiesAsync(this Page page, string cookiesPath) 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 {...
Program.cs
Source:Program.cs
...51 // Headless = true52 // });53 // Console.WriteLine("New Page...");54 // var page = await browser.NewPageAsync();55 // var client = await page.Target.CreateCDPSessionAsync();56 // await client.SendAsync("Network.enable");57 // await client.SendAsync("Page.enable");58 // client.MessageReceived += (sender, e) =>59 // {60 // if (e.MessageID == "Network.webSocketFrameReceived")61 // {62 // var payloadData = e.MessageData["response"]["payloadData"].ToString();63 // PlatformEvent match = _updateRegex.Match(payloadData);64 // if (match.Success)65 // {66 // var data = match.Groups[1].Value;67 // try68 // {69 // dynamic json = JsonConvert.DeserializeObject(data);...
Target.cs
Source:Target.cs
...107 /// <summary>108 /// Creates a Chrome Devtools Protocol session attached to the target.109 /// </summary>110 /// <returns>A task that returns a <see cref="CDPSession"/></returns>111 public Task<CDPSession> CreateCDPSessionAsync() => Browser.Connection.CreateSessionAsync(_targetInfo);112 }113}...
CreateCDPSessionTests.cs
Source:CreateCDPSessionTests.cs
...15 }16 [Fact]17 public async Task ShouldWork()18 {19 var client = await Page.Target.CreateCDPSessionAsync();20 await Task.WhenAll(21 client.SendAsync("Runtime.enable"),22 client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest { Expression = "window.foo = 'bar'" })23 );24 var foo = await Page.EvaluateExpressionAsync<string>("window.foo");25 Assert.Equal("bar", foo);26 }27 [Fact]28 public async Task ShouldSendEvents()29 {30 var client = await Page.Target.CreateCDPSessionAsync();31 await client.SendAsync("Network.enable");32 var events = new List<object>();33 client.MessageReceived += (sender, e) =>34 {35 if (e.MessageID == "Network.requestWillBeSent")36 {37 events.Add(e.MessageData);38 }39 };40 await Page.GoToAsync(TestConstants.EmptyPage);41 Assert.Single(events);42 }43 [Fact]44 public async Task ShouldEnableAndDisableDomainsIndependently()45 {46 var client = await Page.Target.CreateCDPSessionAsync();47 await client.SendAsync("Runtime.enable");48 await client.SendAsync("Debugger.enable");49 // JS coverage enables and then disables Debugger domain.50 await Page.Coverage.StartJSCoverageAsync();51 await Page.Coverage.StopJSCoverageAsync();52 // generate a script in page and wait for the event.53 var eventTask = WaitEvent(client, "Debugger.scriptParsed");54 await Task.WhenAll(55 eventTask,56 Page.EvaluateExpressionAsync("//# sourceURL=foo.js")57 );58 // expect events to be dispatched.59 Assert.Equal("foo.js", eventTask.Result["url"].Value<string>());60 }61 [Fact]62 public async Task ShouldBeAbleToDetachSession()63 {64 var client = await Page.Target.CreateCDPSessionAsync();65 await client.SendAsync("Runtime.enable");66 var evalResponse = await client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest67 {68 Expression = "1 + 2",69 ReturnByValue = true70 });71 Assert.Equal(3, evalResponse["result"]["value"].ToObject<int>());72 await client.DetachAsync();73 var exception = await Assert.ThrowsAnyAsync<Exception>(()74 => client.SendAsync("Runtime.evaluate", new RuntimeEvaluateRequest75 {76 Expression = "3 + 1",77 ReturnByValue = true78 }));79 Assert.Contains("Session closed.", exception.Message);80 }81 [Fact]82 public async Task ShouldThrowNiceErrors()83 {84 var client = await Page.Target.CreateCDPSessionAsync();85 async Task TheSourceOfTheProblems() => await client.SendAsync("ThisCommand.DoesNotExist");86 var exception = await Assert.ThrowsAsync<MessageException>(async () =>87 {88 await TheSourceOfTheProblems();89 });90 Assert.Contains("TheSourceOfTheProblems", exception.StackTrace);91 Assert.Contains("ThisCommand.DoesNotExist", exception.Message);92 }93 }94}...
CreateCDPSessionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });9 var page = await browser.NewPageAsync();10 var client = await target.CreateCDPSessionAsync();11 await client.SendAsync("Network.enable");12 await client.SendAsync("Network.clearBrowserCookies");13 await page.WaitFor(5000);14 await browser.CloseAsync();15 }16 }17}18using System;19using System.Threading.Tasks;20using PuppeteerSharp;21{22 {23 static async Task Main(string[] args)24 {25 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });26 var page = await browser.NewPageAsync();27 var client = await page.CreateCDPSessionAsync();28 await client.SendAsync("Network.enable");29 await client.SendAsync("Network.clearBrowserCookies");30 await page.WaitFor(5000);31 await browser.CloseAsync();32 }33 }34}35using System;36using System.Threading.Tasks;37using PuppeteerSharp;38{39 {40 static async Task Main(string[] args)41 {42 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });43 var page = await browser.NewPageAsync();44 var client = await browser.CreateCDPSessionAsync(page);45 await client.SendAsync("Network.enable");46 await client.SendAsync("Network.clearBrowserCookies");47 await page.WaitFor(5000);48 await browser.CloseAsync();49 }50 }51}52using System;53using System.Threading.Tasks;54using PuppeteerSharp;55{
CreateCDPSessionAsync
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--disable-extensions" }4});5var page = await browser.NewPageAsync();6var target = page.Target;7var session = await target.CreateCDPSessionAsync();8await session.SendAsync("Network.enable");9await session.SendAsync("Network.disable");10await session.DisposeAsync();11await browser.CloseAsync();12var browser = await Puppeteer.LaunchAsync(new LaunchOptions13{14 Args = new string[] { "--disable-extensions" }15});16var page = await browser.NewPageAsync();17var session = await page.CreateCDPSessionAsync();18await session.SendAsync("Network.enable");19await session.SendAsync("Network.disable");20await session.DisposeAsync();21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24 Args = new string[] { "--disable-extensions" }25});26var page = await browser.NewPageAsync();27var session = await browser.CreateCDPSessionAsync(page, "Network.enable");28await session.SendAsync("Network.disable");29await session.DisposeAsync();30await browser.CloseAsync();31var browser = await Puppeteer.LaunchAsync(new LaunchOptions32{33 Args = new string[] { "--disable-extensions" }34});35var page = await browser.NewPageAsync();36var session = await browser.CreateCDPSessionAsync(page, "Network.enable");
CreateCDPSessionAsync
Using AI Code Generation
1var target = await browser.NewPageAsync();2var client = await target.CreateCDPSessionAsync();3await client.SendAsync("Network.enable");4await client.SendAsync("Page.enable");5await client.SendAsync("Page.loadEventFired");6var screenshot = await target.ScreenshotDataAsync();7System.IO.File.WriteAllBytes("screenshot.png", screenshot);8var page = await browser.NewPageAsync();9var client = await page.CreateCDPSessionAsync();10await client.SendAsync("Network.enable");11await client.SendAsync("Page.enable");12await client.SendAsync("Page.loadEventFired");13var screenshot = await page.ScreenshotDataAsync();14System.IO.File.WriteAllBytes("screenshot.png", screenshot);15var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });16var client = await browser.CreateCDPSessionAsync();17await client.SendAsync("Network.enable");18await client.SendAsync("Page.enable");19await client.SendAsync("Page.loadEventFired");20var page = await browser.NewPageAsync();21var screenshot = await page.ScreenshotDataAsync();22System.IO.File.WriteAllBytes("screenshot.png", screenshot);23var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });24var client = await browser.CreateCDPSessionAsync();25await client.SendAsync("Network.enable");26await client.SendAsync("Page.enable");27await client.SendAsync("Page.loadEventFired");28var page = await browser.NewPageAsync();29var screenshot = await page.ScreenshotDataAsync();30System.IO.File.WriteAllBytes("screenshot.png", screenshot);
CreateCDPSessionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 MainAsync().GetAwaiter().GetResult();9 }10 static async Task MainAsync()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"15 });16 var page = await browser.NewPageAsync();17 var session = await target.CreateCDPSessionAsync();18 await session.SendAsync("Page.enable");19 }20 }21}22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 {27 static void Main(string[] args)28 {29 MainAsync().GetAwaiter().GetResult();30 }31 static async Task MainAsync()32 {33 var browser = await Puppeteer.LaunchAsync(new LaunchOptions34 {35 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"36 });37 var page = await browser.NewPageAsync();38 var session = await page.CreateCDPSessionAsync();39 await session.SendAsync("Page.enable");40 }41 }42}43using System;44using System.Threading.Tasks;45using PuppeteerSharp;46{47 {48 static void Main(string[] args)49 {50 MainAsync().GetAwaiter().GetResult();51 }52 static async Task MainAsync()53 {54 var browser = await Puppeteer.LaunchAsync(new LaunchOptions55 {56 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"57 });
CreateCDPSessionAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 Console.WriteLine("Hello World!");9 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions10 {11 }))12 {13 var page = await browser.NewPageAsync();14 var target = await page.Target.CreateCDPSessionAsync();15 await target.SendAsync("Network.enable");16 await target.SendAsync("Network.setCacheDisabled", new { cacheDisabled = true });17 await target.SendAsync("Network.setUserAgentOverride", new { userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36" });18 }19 }20 }21}22using System;23using System.Threading.Tasks;24using PuppeteerSharp;25{26 {27 static async Task Main(string[] args)28 {29 Console.WriteLine("Hello World!");30 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions31 {32 }))33 {34 var page = await browser.NewPageAsync();35 var target = await page.Target.CreateCDPSessionAsync();36 await target.SendAsync("Network.enable");37 await target.SendAsync("Network.setCacheDisabled", new { cacheDisabled = true });38 await target.SendAsync("Network.setUserAgentOverride", new { userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/
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!!