Best Puppeteer-sharp code snippet using PuppeteerSharp.Puppeteer.LaunchAsync
SaveWebPage.xaml.cs
Source:SaveWebPage.xaml.cs
...35 try36 {37 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);3839 var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions40 {41 Headless = true42 });4344 var page = await browser.NewPageAsync(); //æå¼ä¸ä¸ªæ°æ ç¾45 await page.GoToAsync(this.tbox_Url.Text); //访é®é¡µé¢4647 //设置æªå¾é项48 PuppeteerSharp.ScreenshotOptions screenshotOptions = new PuppeteerSharp.ScreenshotOptions();49 //screenshotOptions.Clip = new PuppeteerSharp.Media.Clip() { Height = 0, Width = 0, X = 0, Y = 0 };//设置æªåªåºå50 screenshotOptions.FullPage = true; //æ¯å¦æªåæ´ä¸ªé¡µé¢51 screenshotOptions.OmitBackground = false;//æ¯å¦ä½¿ç¨éæèæ¯ï¼èä¸æ¯é»è®¤ç½è²èæ¯52 screenshotOptions.Quality = 100; //æªå¾è´¨é 0-100ï¼pngä¸å¯ç¨ï¼53 screenshotOptions.Type = PuppeteerSharp.ScreenshotType.Jpeg; //æªå¾æ ¼å¼5455 var fileName = Environment.CurrentDirectory + $"\\download\\{await page.GetTitleAsync()}.jpg";5657 if (System.IO.File.Exists(fileName))58 {59 fileName = fileName.Replace(".jpg", $"{DateTime.Now.ToString("ffff")}.jpg");60 }6162 await page.ScreenshotAsync(fileName, screenshotOptions);6364 if (System.IO.File.Exists(fileName))65 {66 BitmapImage bi = new BitmapImage();67 bi.BeginInit();68 bi.UriSource = new Uri(fileName, UriKind.Absolute);69 bi.EndInit();70 this.image.Source = bi;71 }72 else73 {74 EMessageBox.Show("ä¿åç½é¡µæªå¾å¤±è´¥");75 }7677 //å¨æåè®°å¾å
³éæµè§å¨åéæ¾èµæº78 browser.Disconnect();79 browser.Dispose();80 }81 catch(Exception ex)82 {83 EMessageBox.Show(ex.Message);84 }85 }8687 private async void btn_SaveAsPDF_Click(object sender, RoutedEventArgs e)88 {89 //æå¼ç½é¡µçæä½è·ä¸é¢æ¯ä¸æ ·ç90 try91 {92 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);93 var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions94 {95 Headless = true96 });97 var page = await browser.NewPageAsync(); //æå¼ä¸ä¸ªæ°æ ç¾98 await page.GoToAsync(this.tbox_Url.Text); //访é®é¡µé¢99100 //设置PDFé项101 PuppeteerSharp.PdfOptions pdfOptions = new PuppeteerSharp.PdfOptions();102 pdfOptions.DisplayHeaderFooter = false; //æ¯å¦æ¾ç¤ºé¡µç页è103 pdfOptions.FooterTemplate = ""; //页èææ¬104105 var width = await page.EvaluateFunctionAsync<int>("function getWidth(){return document.body.scrollWidth}");106 var height = await page.EvaluateFunctionAsync<int>("function getHeight(){return document.body.scrollHeight}");107
...
Form1.cs
Source:Form1.cs
...19 }20 private async void button1_Click(object sender, EventArgs e)21 { 22 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);23 browser = await Puppeteer.LaunchAsync(new LaunchOptions24 {25 Headless = true26 });27 //å¦æawait new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);æ§è¡ä¸æå28 //å¯ä»¥æå¨è®¿é®https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win_x64/ï¼ä¸è½½Chromiumæµè§å¨ï¼å¹¶è§£åå°æå®ä½ç½®29 //åéè¿ä»¥ä¸ä»£ç åå§å30 /*31 * LaunchOptions options = new LaunchOptions();32 options.Headless = true;33 options.DefaultViewport = null;34 //忽ç¥è¯ä¹¦é误35 options.IgnoreHTTPSErrors = true;36 //chromePathå°±æ¯ä¸è½½çChromiumæµè§å¨è§£åçä½ç½® 37 options.ExecutablePath = chromePath;38 browser = await Puppeteer.LaunchAsync(options);39 */40 var page = await browser.NewPageAsync();41 await page.GoToAsync(this.textBox1.Text);42 var html = await page.GetContentAsync();43 this.richTextBox1.Text = html;44 }45 private async void button2_Click(object sender, EventArgs e)46 {47 //è·åæåçæ ç¾é¡µ48 var page = (await browser.PagesAsync()).Last();49 var path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"screenshot.jpg");50 //设置æªå¾é项51 ScreenshotOptions screenshotOptions = new ScreenshotOptions();52 //screenshotOptions.Clip = new PuppeteerSharp.Media.Clip() { Height = 0, Width = 0, X = 0, Y = 0 };//设置æªåªåºå...
GistGithubService.cs
Source:GistGithubService.cs
...104 private async Task<Uri> GetRedirectCallbackResult(Uri redirectPage)105 {106 var revisionInfo = await browserFetcher107 .DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);108 using var browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions109 {110 Headless = false,111 LogProcess = true,112 DumpIO = true113 });114 var page = await browser.NewPageAsync();115 var redirectResult = await page.GoToAsync(redirectPage.AbsoluteUri);116 var target = await browser.WaitForTargetAsync(e => e.Url.Contains(gitHubModel.RedirectUrl!));117 return new Uri(target.Url);118 }119 }120}...
Program.cs
Source:Program.cs
...12 static void Main(string[] args)13 {14 /*15 2020-02-17 Observation before introducing the killing of previous web browser processes:16 LaunchAsync failed if a process from the last run was still present.17 (See report of this issue at https://forum.botengine.org/t/farm-manager-tribal-wars-2-farmbot/3038/32?u=viir)18 Unhandled exception. System.AggregateException: One or more errors occurred. (Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)19 [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_00020 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache21 [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -222 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.23 )24 ---> PuppeteerSharp.ChromiumProcessException: Failed to launch Chromium! [28592:33396:0217/074915.470:ERROR:cache_util_win.cc(21)] Unable to move the cache: Access is denied. (0x5)25 [28592:33396:0217/074915.471:ERROR:cache_util.cc(141)] Unable to move cache folder C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\GPUCache to C:\Users\John\AppData\Local\bot\web-browser\user-data\ShaderCache\old_GPUCache_00026 [28592:33396:0217/074915.471:ERROR:disk_cache.cc(178)] Unable to create cache27 [28592:33396:0217/074915.471:ERROR:shader_disk_cache.cc(601)] Shader Cache Creation failed: -228 [28592:33396:0217/074915.473:ERROR:browser_gpu_channel_host_factory.cc(138)] Failed to launch GPU process.29 at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)30 at PuppeteerSharp.ChromiumProcess.State.StartingState.StartCoreAsync(ChromiumProcess p)31 at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)32 at PuppeteerSharp.Launcher.LaunchAsync(LaunchOptions options)33 */34 KillPreviousWebBrowserProcesses();35 StartWebBrowser().Wait();36 }37 static void KillPreviousWebBrowserProcesses()38 {39 var matchingProcesses =40 System.Diagnostics.Process.GetProcesses()41 /*42 2020-02-1743 .Where(process => process.StartInfo.Arguments.Contains(UserDataDirPath(), StringComparison.InvariantCultureIgnoreCase))44 */45 .Where(ProcessIsWebBrowser)46 .ToList();47 foreach (var process in matchingProcesses)48 {49 if (process.HasExited)50 continue;51 process.Kill();52 }53 }54 static bool ProcessIsWebBrowser(System.Diagnostics.Process process)55 {56 try57 {58 return process.MainModule.FileName.Contains(".local-chromium");59 }60 catch61 {62 return false;63 }64 }65 static async System.Threading.Tasks.Task StartWebBrowser()66 {67 await new PuppeteerSharp.BrowserFetcher().DownloadAsync(PuppeteerSharp.BrowserFetcher.DefaultRevision);68 browser = await PuppeteerSharp.Puppeteer.LaunchAsync(new PuppeteerSharp.LaunchOptions69 {70 Headless = false,71 UserDataDir = UserDataDirPath(),72 DefaultViewport = null,73 });74 browserPage = (await browser.PagesAsync()).FirstOrDefault() ?? await browser.NewPageAsync();75 await browserPage.ExposeFunctionAsync("____callback____", (string returnValue) =>76 {77 callbackFromBrowserDelegate?.Invoke(returnValue);78 return 0;79 });80 }81 }82}...
PuppeteerGenerator.cs
Source:PuppeteerGenerator.cs
...29 var options = new LaunchOptions {30 Headless = true,31 ExecutablePath = chromePath32 };33 return await Puppeteer.LaunchAsync(options);34 }35 private static void PutBrowser(Browser item) {36 _browsers.Add(item);37 }38 public async Task<Stream> Generate(string htmlSource, bool includeFooters, PdfPageSettings settings) {39 //if (string.IsNullOrEmpty(PuppeteerPath))40 // throw new ArgumentNullException();41 //// check if chromium exists, then download if not42 //var chromePath = Path.Combine(PuppeteerPath, "chrome-win\\chrome.exe");43 //if (!File.Exists(chromePath)) {44 // chromePath = await DownloadPuppeteerToPath(PuppeteerPath);45 //}46 //var options = new LaunchOptions {47 // Headless = true,48 // ExecutablePath = chromePath49 //};50 //using (var browser = await Puppeteer.LaunchAsync(options)) {51 var browser = await GetBrowser();52 try {53 using (var page = await browser.NewPageAsync()) {54 await page.SetContentAsync(htmlSource);55 var result = await page.GetContentAsync();56 var pdfOptions = GetPdfOptions(includeFooters, settings);57 return await page.PdfStreamAsync(pdfOptions);58 }59 } finally {60 PutBrowser(browser);61 }62 //}63 }64 public IPdfGenerator AddHeader(string text, bool isLeft = true) {...
DocumentsV2Controller.cs
Source:DocumentsV2Controller.cs
...34 return Ok(new { Paths = files.Select(x => "/pdf/" + x), Elapsed = stopwatch.ElapsedMilliseconds });35 }36 [NonAction]37 public async Task<List<string>> GeneratePdfAsync(List<IFormFile> streams, bool landscape) {38 s_browser ??= await Puppeteer.LaunchAsync(_browserOptions);39 var tasks = streams.Select(async x => {40 using (StreamReader stringReader = new StreamReader(x.OpenReadStream()))41 using (var page = await s_browser.NewPageAsync()) {42 await page.SetContentAsync(await stringReader.ReadToEndAsync());43 var fileName = $"{Guid.NewGuid()}.pdf";44 await page.PdfAsync($"{Directory.GetCurrentDirectory()}/files/{fileName}", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });45 return fileName;46 }47 });48 var files = await Task.WhenAll(tasks);49 return files.ToList();50 }51 [NonAction]52 public async Task<List<string>> GeneratePdfAsync(List<string> url, bool landscape) {53 s_browser ??= await Puppeteer.LaunchAsync(_browserOptions);54 var tasks = url.Select(async x => {55 using (var page = await s_browser.NewPageAsync()) {56 await page.GoToAsync(x);57 var fileName = $"{Guid.NewGuid()}.pdf";58 await page.PdfAsync($"{Directory.GetCurrentDirectory()}/files/{fileName}", new PdfOptions() { Format = PuppeteerSharp.Media.PaperFormat.A4, Landscape = landscape, OmitBackground = true, PrintBackground = true });59 return fileName;60 }61 });62 var files = await Task.WhenAll(tasks);63 return files.ToList();64 }65 }66}...
PuppeteerUtility.csx
Source:PuppeteerUtility.csx
...8 }9 return chromeProcs.First().Modules[0].FileName;10 }11 public async static Task<PageResult> GetPage(){12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 Headless = false,15 ExecutablePath = findChrome(),16 Args = new[]{ "--app=http://localhost/null" }17 });18 var page = (await browser.PagesAsync())[0];19 //await page.WaitForNavigationAsync();20 return new PageResult{21 Browser = browser, // they may need the browser to close it after they are done22 Page = page23 };24 }25 26}...
PuppeteerDocumentGenerator.cs
Source:PuppeteerDocumentGenerator.cs
...7 {8 public async Task<byte[]> Generate(string html)9 {10 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);11 var browser = await Puppeteer.LaunchAsync(new LaunchOptions12 {13 Headless = true,14 // If needed, we can specify a specific version of Chrome15 //ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",16 //IgnoredDefaultArgs = new string[] { "--disable-extensions" },17 //IgnoreDefaultArgs = true,18 });19 using (var page = await browser.NewPageAsync())20 {21 await page.SetContentAsync(html);22 var pdfData = await page.PdfDataAsync(new PdfOptions23 {24 MarginOptions = new MarginOptions25 {...
LaunchAsync
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 LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 }13 }14}15using System;16using System.Threading.Tasks;17using PuppeteerSharp;18{19 {20 static async Task Main(string[] args)21 {22 var browser = await Puppeteer.LaunchAsync(new LaunchOptions23 {24 {25 }26 });27 var page = await browser.NewPageAsync();28 }29 }30}31using System;32using System.Threading.Tasks;33using PuppeteerSharp;34{35 {36 static async Task Main(string[] args)37 {38 var browser = await Puppeteer.LaunchAsync(new LaunchOptions39 {40 {41 }42 });43 var page = await browser.NewPageAsync();
LaunchAsync
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 Args = new string[] { "--no-sandbox" }4});5var page = await browser.NewPageAsync();6await page.ScreenshotAsync("google.png");7var browser = await Puppeteer.LaunchAsync(new LaunchOptions8{9 Args = new string[] { "--no-sandbox" }10});11var page = await browser.NewPageAsync();12await page.ScreenshotAsync("google.png");13var browser = await Puppeteer.LaunchAsync(new LaunchOptions14{15 Args = new string[] { "--no-sandbox" }16});17var page = await browser.NewPageAsync();18await page.ScreenshotAsync("google.png");19var browser = await Puppeteer.LaunchAsync(new LaunchOptions20{21 Args = new string[] { "--no-sandbox" }22});23var page = await browser.NewPageAsync();24await page.ScreenshotAsync("google.png");25var browser = await Puppeteer.LaunchAsync(new LaunchOptions26{27 Args = new string[] { "--no-sandbox" }28});29var page = await browser.NewPageAsync();30await page.ScreenshotAsync("google.png");31var browser = await Puppeteer.LaunchAsync(new LaunchOptions32{33 Args = new string[] { "--no-sandbox" }34});35var page = await browser.NewPageAsync();36await page.ScreenshotAsync("google.png
LaunchAsync
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2{3 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"4});5var page = await browser.NewPageAsync();6await page.ScreenshotAsync("google.png");7await browser.CloseAsync();8var browser = await Puppeteer.LaunchAsync(new LaunchOptions9{10 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"11});12var page = await browser.NewPageAsync();13await page.ScreenshotAsync("google.png");14await browser.CloseAsync();15var browser = await Puppeteer.LaunchAsync(new LaunchOptions16{17 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"18});19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("google.png");21await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23{24 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"25});26var page = await browser.NewPageAsync();27await page.ScreenshotAsync("google.png");28await browser.CloseAsync();29var browser = await Puppeteer.LaunchAsync(new LaunchOptions30{31 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"32});33var page = await browser.NewPageAsync();34await page.ScreenshotAsync("google.png");35await browser.CloseAsync();
LaunchAsync
Using AI Code Generation
1var options = new LaunchOptions { Headless = true };2var browser = await Puppeteer.LaunchAsync(options);3var page = await browser.NewPageAsync();4await page.ScreenshotAsync("screen.png");5var options = new LaunchOptions { Headless = false };6var browser = await Puppeteer.LaunchAsync(options);7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("screen.png");9var options = new LaunchOptions { Headless = false };10var browser = await Puppeteer.LaunchAsync(options);11var page = await browser.NewPageAsync();12await page.ScreenshotAsync("screen.png");13var options = new LaunchOptions { Headless = false };14var browser = await Puppeteer.LaunchAsync(options);15var page = await browser.NewPageAsync();16await page.ScreenshotAsync("screen.png");17var options = new LaunchOptions { Headless = false };18var browser = await Puppeteer.LaunchAsync(options);19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("screen.png");21var options = new LaunchOptions { Headless = false };22var browser = await Puppeteer.LaunchAsync(options);23var page = await browser.NewPageAsync();24await page.ScreenshotAsync("screen.png");25var options = new LaunchOptions { Headless = false };26var browser = await Puppeteer.LaunchAsync(options);27var page = await browser.NewPageAsync();
LaunchAsync
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 var browser = await Puppeteer.LaunchAsync(options);11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("screenshot.png");13 await browser.CloseAsync();14 }15 }16}
LaunchAsync
Using AI Code Generation
1{2 Args = new[] { "--no-sandbox" }3};4var browser = await Puppeteer.LaunchAsync(options);5var page = await browser.NewPageAsync();6await page.ScreenshotAsync("google.png");7await browser.CloseAsync();8{9 Args = new[] { "--no-sandbox" }10};11var browser = await Puppeteer.LaunchAsync(options);12var page = await browser.NewPageAsync();13await page.ScreenshotAsync("google.png");14await browser.CloseAsync();15{16 Args = new[] { "--no-sandbox" }17};18var browser = await Puppeteer.LaunchAsync(options);19var page = await browser.NewPageAsync();20await page.ScreenshotAsync("google.png");21await browser.CloseAsync();22{23 Args = new[] { "--no-sandbox" }24};25var browser = await Puppeteer.LaunchAsync(options);26var page = await browser.NewPageAsync();27await page.ScreenshotAsync("google.png");28await browser.CloseAsync();29{30 Args = new[] { "--no-sandbox" }31};32var browser = await Puppeteer.LaunchAsync(options);33var page = await browser.NewPageAsync();34await page.ScreenshotAsync("google.png");35await browser.CloseAsync();36{
LaunchAsync
Using AI Code Generation
1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static void Main(string[] args)7 {8 MainAsync().Wait();9 }10 static async Task MainAsync()11 {12 {13 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"14 };15 using (var browser = await Puppeteer.LaunchAsync(options))16 using (var page = await browser.NewPageAsync())17 {18 Console.WriteLine(await page.GetContentAsync());19 }20 }21 }22}
LaunchAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static void Main(string[] args)7 {8 RunExample().Wait();9 }10 static async Task RunExample()11 {12 var browser = await Puppeteer.LaunchAsync(new LaunchOptions13 {14 });15 var page = await browser.NewPageAsync();16 await page.ScreenshotAsync("google.png");17 await browser.CloseAsync();18 }19 }20}21using System;22using System.Threading.Tasks;23using PuppeteerSharp;24{25 {26 static void Main(string[] args)27 {28 RunExample().Wait();29 }30 static async Task RunExample()31 {32 var browser = await Puppeteer.LaunchAsync(new LaunchOptions33 {34 });35 var page = await browser.NewPageAsync();36 await page.ScreenshotAsync("google.png");37 await browser.CloseAsync();38 }39 }40}41using System;42using System.Threading.Tasks;43using PuppeteerSharp;44{45 {46 static void Main(string[]
LaunchAsync
Using AI Code Generation
1using System.IO;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 });11 var page = await browser.NewPageAsync();12 await page.ScreenshotAsync("2.png");13 await browser.CloseAsync();14 }15 }16}17using System.IO;18using System.Threading.Tasks;19using PuppeteerSharp;20{21 {22 static async Task Main(string[] args)23 {24 var browser = await Puppeteer.LaunchAsync(new LaunchOptions25 {26 });27 var page = await browser.NewPageAsync();28 await page.ScreenshotAsync("3.png");29 await browser.CloseAsync();30 }31 }32}33using System.IO;34using System.Threading.Tasks;35using PuppeteerSharp;36{37 {38 static async Task Main(string[] args)39 {40 var browser = await Puppeteer.LaunchAsync(new LaunchOptions41 {42 });43 var page = await browser.NewPageAsync();44 await page.ScreenshotAsync("4.png");45 await browser.CloseAsync();46 }47 }
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!!