Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.ScreenshotDataAsync
ScreenshotTests.cs
Source:ScreenshotTests.cs
...50 Width = 500,51 Height = 50052 });53 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");54 var screenshot = await page.ScreenshotDataAsync();55 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot));56 }57 }58 [Fact]59 public async Task ShouldClipRect()60 {61 using (var page = await Browser.NewPageAsync())62 {63 await page.SetViewportAsync(new ViewPortOptions64 {65 Width = 500,66 Height = 50067 });68 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");69 var screenshot = await page.ScreenshotDataAsync(new ScreenshotOptions70 {71 Clip = new Clip72 {73 X = 50,74 Y = 100,75 Width = 150,76 Height = 10077 }78 });79 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));80 }81 }82 [Fact]83 public async Task ShouldWorkForOffscreenClip()84 {85 using (var page = await Browser.NewPageAsync())86 {87 await page.SetViewportAsync(new ViewPortOptions88 {89 Width = 500,90 Height = 50091 });92 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");93 var screenshot = await page.ScreenshotDataAsync(new ScreenshotOptions94 {95 Clip = new Clip96 {97 X = 50,98 Y = 600,99 Width = 100,100 Height = 100101 }102 });103 Assert.True(ScreenshotHelper.PixelMatch("screenshot-offscreen-clip.png", screenshot));104 }105 }106 [Fact]107 public async Task ShouldRunInParallel()108 {109 using (var page = await Browser.NewPageAsync())110 {111 await page.SetViewportAsync(new ViewPortOptions112 {113 Width = 500,114 Height = 500115 });116 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");117 var tasks = new List<Task<byte[]>>();118 for (var i = 0; i < 3; ++i)119 {120 tasks.Add(page.ScreenshotDataAsync(new ScreenshotOptions121 {122 Clip = new Clip123 {124 X = 50 * i,125 Y = 0,126 Width = 50,127 Height = 50128 }129 }));130 }131 await Task.WhenAll(tasks);132 Assert.True(ScreenshotHelper.PixelMatch("grid-cell-1.png", tasks[0].Result));133 }134 }135 [Fact]136 public async Task ShouldTakeFullPageScreenshots()137 {138 using (var page = await Browser.NewPageAsync())139 {140 await page.SetViewportAsync(new ViewPortOptions141 {142 Width = 500,143 Height = 500144 });145 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");146 var screenshot = await page.ScreenshotDataAsync(new ScreenshotOptions147 {148 FullPage = true149 });150 Assert.True(ScreenshotHelper.PixelMatch("screenshot-grid-fullpage.png", screenshot));151 }152 }153 [Fact]154 public async Task ShouldRunInParallelInMultiplePages()155 {156 var n = 2;157 var pageTasks = new List<Task<Page>>();158 for (var i = 0; i < n; i++)159 {160 Func<Task<Page>> func = async () =>161 {162 var page = await Browser.NewPageAsync();163 await page.GoToAsync(TestConstants.ServerUrl + "/grid.html");164 return page;165 };166 pageTasks.Add(func());167 }168 await Task.WhenAll(pageTasks);169 var screenshotTasks = new List<Task<byte[]>>();170 for (var i = 0; i < n; i++)171 {172 screenshotTasks.Add(pageTasks[i].Result.ScreenshotDataAsync(new ScreenshotOptions173 {174 Clip = new Clip175 {176 X = 50 * i,177 Y = 0,178 Width = 50,179 Height = 50180 }181 }));182 }183 await Task.WhenAll(screenshotTasks);184 for (var i = 0; i < n; i++)185 {186 Assert.True(ScreenshotHelper.PixelMatch($"grid-cell-{i}.png", screenshotTasks[i].Result));187 }188 var closeTasks = new List<Task>();189 for (var i = 0; i < n; i++)190 {191 closeTasks.Add(pageTasks[i].Result.CloseAsync());192 }193 await Task.WhenAll(closeTasks);194 }195 [Fact]196 public async Task ShouldAllowTransparency()197 {198 using (var page = await Browser.NewPageAsync())199 {200 await page.SetViewportAsync(new ViewPortOptions201 {202 Width = 100,203 Height = 100204 });205 await page.GoToAsync(TestConstants.EmptyPage);206 var screenshot = await page.ScreenshotDataAsync(new ScreenshotOptions207 {208 OmitBackground = true209 });210 Assert.True(ScreenshotHelper.PixelMatch("transparent.png", screenshot));211 }212 }213 [Fact]214 public async Task ShouldWorkWithOddClipSizeOnRetinaDisplays()215 {216 using (var page = await Browser.NewPageAsync())217 {218 var screenshot = await page.ScreenshotDataAsync(new ScreenshotOptions219 {220 Clip = new Clip221 {222 X = 0,223 Y = 0,224 Width = 11,225 Height = 11226 }227 });228 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-odd-size.png", screenshot));229 }230 }231 }232}...
Program.cs
Source:Program.cs
...41 //await page.GoToAsync("http://192.168.0.107:98/static/index.html#/preview?recordid=059d67fea03a4c3687bc49ac04669968&t=6deb2042ec114ac291fadb2514182352&generate=true", navigationOption);42 await page.GoToAsync("https://zhuangxiu.xxxxxx.com/#/preview?recordid=1095a3231f704b419b8b0676fa8d147e&t=e1859920de894de394c577f802f67167&generate=true", navigationOption);43 44 var o = new ScreenshotOptions { Type = ScreenshotType.Png, FullPage = true };45 var bytes = await page.ScreenshotDataAsync(o);46 var modules = await page.QuerySelectorAllAsync(".screenshot-box");47 var dic=new Dictionary<int, Clip>();48 for (var i = 0; i < modules.Length; i++)49 {50 var module = modules[i];51 var box = await module.BoundingBoxAsync();52 var clip = new Clip { Width = box.Width, Height = box.Height, X = box.X, Y = box.Y };53 dic.Add(i, clip);54 }55 Parallel.For(0, dic.Count, n =>56 {57 //计ç®åºå
ç´ ä¸ãä¸ãå·¦ãå³ ä½ç½®58 var left = (int)dic[n].X;59 var top = (int)dic[n].Y;60 var right = (int)dic[n].Width;61 var bottom = (int)dic[n].Height;62 //å®ä¹æªåç©å½¢63 var cropArea = new Rectangle(left, top, right, bottom); //è¦æªåçåºå大å°64 //å è½½å¾ç65 MemoryStream ms = new MemoryStream(bytes);66 var screenImage = (Bitmap)Image.FromStream(ms);67 //è¿è¡è£åª68 var bmpCrop = screenImage.Clone(cropArea, screenImage.PixelFormat);69 //ä¿åææ°æ件70 bmpCrop.Save($"{n}.png");71 //éæ¾å¯¹è±¡72 screenImage.Dispose();73 });74 75 //await page.ScreenshotAsync($"{j}.png", options);76 //for (var n = 0; n < dic.Count; n++)77 //{78 // //计ç®åºå
ç´ ä¸ãä¸ãå·¦ãå³ ä½ç½®79 // var left = (int)dic[n].X;80 // var top = (int)dic[n].Y;81 // var right = (int)dic[n].Width;82 // var bottom = (int)dic[n].Height;83 // //var codeImagePath = imageDir + fileName + "_crop" + fileSuffix;84 // //å®ä¹æªåç©å½¢85 // var cropArea = new Rectangle(left, top, right, bottom); //è¦æªåçåºå大å°86 // //å è½½å¾ç87 // MemoryStream ms=new MemoryStream(bytes);88 // var screenImage = (Bitmap)Image.FromStream(ms);89 // //è¿è¡è£åª90 // var bmpCrop = screenImage.Clone(cropArea, screenImage.PixelFormat);91 // //ä¿åææ°æ件92 // bmpCrop.Save($"{n}.png");93 // //éæ¾å¯¹è±¡94 // screenImage.Dispose();95 //}96 //for (var j = 0; j < dic.Count; j++)97 //{98 // var options = new ScreenshotOptions { Type = ScreenshotType.Png, Clip = dic[j] };99 // //await page.ScreenshotDataAsync(options);100 // await page.ScreenshotAsync($"{j}.png", options);101 //}102 sw.Stop();103 await page.CloseAsync();104 await browser.CloseAsync();105 Console.WriteLine($"success!{sw.Elapsed.TotalSeconds}");106 Console.ReadKey();107 }108 }109}...
PageEmulateVisionDeficiencyTests.cs
Source:PageEmulateVisionDeficiencyTests.cs
...17 {18 await Page.SetViewportAsync(new ViewPortOptions { Width = 500, Height = 500 });19 await Page.GoToAsync(TestConstants.ServerUrl + "/grid.html");20 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.None);21 var screenshot = await Page.ScreenshotDataAsync();22 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot));23 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.Achromatopsia);24 screenshot = await Page.ScreenshotDataAsync();25 Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-achromatopsia.png", screenshot));26 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.BlurredVision);27 screenshot = await Page.ScreenshotDataAsync();28 Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-blurredVision.png", screenshot));29 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.Deuteranopia);30 screenshot = await Page.ScreenshotDataAsync();31 Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-deuteranopia.png", screenshot));32 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.Protanopia);33 screenshot = await Page.ScreenshotDataAsync();34 Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-protanopia.png", screenshot));35 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.Tritanopia);36 screenshot = await Page.ScreenshotDataAsync();37 Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-tritanopia.png", screenshot));38 await Page.EmulateVisionDeficiencyAsync(VisionDeficiency.None);39 screenshot = await Page.ScreenshotDataAsync();40 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot));41 }42 }43}
ScreenshotLoader.cs
Source:ScreenshotLoader.cs
...40 Width = Options.Value.ScreenshotWidth, 41 Height = Options.Value.ScreenshotHeight 42 });43 await page.GoToAsync(source);44 byte[] buffer = await page.ScreenshotDataAsync(new ScreenshotOptions() { Type = ScreenshotType.Png });45 return new OriginalData(MimeTypes.Png, new MemoryStream(buffer), new CacheSettings().ApplyLoaderOptions(Options.Value));46 }47}...
WebBrowser.cs
Source:WebBrowser.cs
...46 {47 using (var page = await browser.NewPageAsync())48 {49 await page.GoToAsync(url);50 var result = await page.ScreenshotDataAsync();51 return result;52 }53 }54 }55 }56}...
HtmlToImage.cs
Source:HtmlToImage.cs
...47 {48 var buff = Convert.FromBase64String(dto.HtmlBase64);49 var text = UTF8Encoding.UTF8.GetString(buff);50 await page.SetContentAsync(text);51 var image = await page.ScreenshotDataAsync();52 return new FileContentResult(image, "image/png");53 }54 }55 }56}
Url2PngSingle.Puppeteer.cs
Source:Url2PngSingle.Puppeteer.cs
...18 Chrome.logger.Debug($"{instance.Name}: Screenshot GoToUrl {url}");19 instance.Page().GoToAsync(url).Wait();20 System.Threading.Thread.Sleep(50);21 Chrome.logger.Debug($"{instance.Name}: Screenshot GetScreenshot {url}");22 var screenshot = instance.Page().ScreenshotDataAsync().Result;23 Chrome.logger.Debug($"{instance.Name}: Screenshot Cropping {url}");24 using (Devmasters.Imaging.InMemoryImage img = new Devmasters.Imaging.InMemoryImage(screenshot))25 {26 img.Crop(new System.Drawing.Rectangle(0, 0, cropWidth, cropHeight));27 using (System.IO.MemoryStream ms = new System.IO.MemoryStream())28 {29 img.SaveAsPNG(ms);30 return ms.ToArray();31 }32 }33 }34 catch (Exception e)35 {36 Chrome.logger.Error($"{instance.Name}: Screenshot Error {url}", e);...
GithubController.cs
Source:GithubController.cs
...23 {24 await page.GoToAsync(contributorsPage);25 await page.WaitForSelectorAsync("#contributors");26 var element = await page.QuerySelectorAsync("#contributors");27 var image = await element.ScreenshotDataAsync();28 return File(image, "image/png");29 }30 }31 }32}
...
ScreenshotDataAsync
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 LaunchOptions10 {11 Args = new string[] { "--no-sandbox" }12 });13 var page = await browser.NewPageAsync();14 var screenshot = await page.ScreenshotDataAsync();15 System.IO.File.WriteAllBytes("google.png", screenshot);16 await browser.CloseAsync();17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);28 var browser = await Puppeteer.LaunchAsync(new LaunchOptions29 {30 Args = new string[] { "--no-sandbox" }31 });32 var page = await browser.NewPageAsync();33 var screenshotStream = await page.ScreenshotStreamAsync();34 using (var fileStream = System.IO.File.Create("google.png"))35 {36 await screenshotStream.CopyToAsync(fileStream);37 }38 await browser.CloseAsync();39 }40 }41}42using System;43using System.Threading.Tasks;44using PuppeteerSharp;45{46 {47 static async Task Main(string[] args)48 {49 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);50 var browser = await Puppeteer.LaunchAsync(new LaunchOptions51 {52 Args = new string[] { "--no-sandbox" }53 });54 var page = await browser.NewPageAsync();55 await page.ScreenshotAsync("google.png");56 await browser.CloseAsync();57 }58 }59}
ScreenshotDataAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 {9 };10 using (var browser = await Puppeteer.LaunchAsync(options))11 {12 using (var page = await browser.NewPageAsync())13 {14 var screenshot = await page.ScreenshotDataAsync();15 System.IO.File.WriteAllBytes("screenshot.png", screenshot);16 }17 }18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static async Task Main(string[] args)27 {28 {29 };30 using (var browser = await Puppeteer.LaunchAsync(options))31 {32 using (var page = await browser.NewPageAsync())33 {34 var screenshot = await page.ScreenshotDataAsync();35 System.IO.File.WriteAllBytes("screenshot.png", screenshot);36 }37 }38 }39 }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45 {46 static async Task Main(string[] args)47 {48 {49 };50 using (var browser = await Puppeteer.LaunchAsync(options))51 {52 using (var page = await browser.NewPageAsync())53 {54 var screenshot = await page.ScreenshotDataAsync();55 System.IO.File.WriteAllBytes("screenshot.png", screenshot);56 }57 }58 }59 }60}61using System;62using System.Threading.Tasks;63using PuppeteerSharp;64{65 {66 static async Task Main(string[] args)
ScreenshotDataAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.ScreenshotDataAsync();3var page = await browser.NewPageAsync();4await page.ScreenshotDataAsync();5var page = await browser.NewPageAsync();6await page.ScreenshotDataAsync();7var page = await browser.NewPageAsync();8await page.ScreenshotDataAsync();9var page = await browser.NewPageAsync();10await page.ScreenshotDataAsync();11var page = await browser.NewPageAsync();12await page.ScreenshotDataAsync();13var page = await browser.NewPageAsync();14await page.ScreenshotDataAsync();15var page = await browser.NewPageAsync();16await page.ScreenshotDataAsync();
ScreenshotDataAsync
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6 {7 static async Task Main(string[] args)8 {9 {10 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",11 Args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }12 };13 using (var browser = await Puppeteer.LaunchAsync(options))14 {15 using (var page = await browser.NewPageAsync())16 {17 var screenshot = await page.ScreenshotDataAsync();18 await File.WriteAllBytesAsync("google.png", screenshot);19 }20 }21 }22 }23}
ScreenshotDataAsync
Using AI Code Generation
1{2 {3 public ScreenshotData(byte[] data, string type)4 {5 Data = data;6 Type = type;7 }8 public byte[] Data { get; }9 public string Type { get; }10 }11 {12 public async Task<ScreenshotData> ScreenshotDataAsync(ScreenshotOptions options = null)13 {14 var data = await ScreenshotDataAsync(options).ConfigureAwait(false);15 return new ScreenshotData(data, "png");16 }17 }18}19{20 {21 public ScreenshotData(byte[] data, string type)22 {23 Data = data;24 Type = type;25 }26 public byte[] Data { get; }27 public string Type { get; }28 }29 {30 public async Task<ScreenshotData> ScreenshotDataAsync(ScreenshotOptions options = null)31 {32 var data = await ScreenshotDataAsync(options).ConfigureAwait(false);33 return new ScreenshotData(data, "png");34 }35 }36}37{38 {39 public ScreenshotData(byte[] data, string type)40 {41 Data = data;42 Type = type;43 }44 public byte[] Data { get; }45 public string Type { get; }46 }47 {48 public async Task<ScreenshotData> ScreenshotDataAsync(ScreenshotOptions options = null)49 {50 var data = await ScreenshotDataAsync(options).ConfigureAwait(false);51 return new ScreenshotData(data, "png");52 }53 }54}55var screenshotData = await page.ScreenshotDataAsync();56var screenshotData = await page.ScreenshotDataAsync();57await File.WriteAllBytesAsync("screenshot.png", screenshotData.Data);
ScreenshotDataAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2var screenshot = await page.ScreenshotDataAsync();3File.WriteAllBytes("./screenshot.png", screenshot);4var page = await browser.NewPageAsync();5using (var stream = await page.ScreenshotStreamAsync())6using (var fileStream = File.Create("./screenshot.png"))7{8 await stream.CopyToAsync(fileStream);9}10var page = await browser.NewPageAsync();11await page.ScreenshotAsync("./screenshot.png");
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!!