Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.Cleanup
BrowserUtils.cs
Source:BrowserUtils.cs
...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) {181 await page.CloseAsync();182 }183 private void Cleanup(PuppeteerSharp.Browser browser) {184 browser.Disconnect();185 Dispose();186 }187 public void Dispose() {188 if (browser != null) {189 ProcessUtils.KillProcessTree(browser.Process);190 }191 }192 }193}...
PuppeteerBrowser.cs
Source:PuppeteerBrowser.cs
1using PuppeteerSharp;2using System;3namespace HlidacStatu.Util.WebShot4{5 public class PuppeteerBrowser : IDisposable6 {7 static PuppeteerBrowser()8 {9 new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision).Wait();10 }11 public static Devmasters.Core.Logging.Logger logger = new Devmasters.Core.Logging.Logger("HlidacStatu.Util.Webshots");12 private static readonly PuppeteerBrowser theOnlyInstance = new PuppeteerBrowser("theOnlyInstance");13 public static PuppeteerBrowser TheOnlyStaticInstance14 {15 get16 {17 return theOnlyInstance;18 }19 }20 PuppeteerSharp.Browser browser = null;21 PuppeteerSharp.Page page = null;22 int width = 00;23 int height = 0;24 public string Name { get; set; } = null;25 public PuppeteerBrowser(string name = null)26 : this(1920, 1080, name)27 {28 }29 public PuppeteerBrowser(int displaywidth, int displayheight, string name = null)30 {31 this.width = displaywidth;32 this.height = displayheight;33 this.Name = "PuppeteerBrowser-" + (name ?? Devmasters.Core.TextUtil.GenRandomString(10));34 Init();35 }36 private void Init()37 {38 logger.Debug($"{this.Name}: Initiating PuppeteerBrowser");39 var chromeBinaryFileName = Devmasters.Core.Util.Config.GetConfigValue("ChromeBinaryFullPath");40 var launchOptions = new LaunchOptions()41 {42 Headless = true,43 DefaultViewport = new ViewPortOptions()44 {45 DeviceScaleFactor = 1,46 IsLandscape = false,47 HasTouch = false,48 IsMobile = false,49 Height = this.height,50 Width = this.width,51 }52 };53 if (!string.IsNullOrEmpty(chromeBinaryFileName))54 launchOptions.ExecutablePath = chromeBinaryFileName;55 this.browser = Puppeteer.LaunchAsync(launchOptions).Result;56 this.page = browser.NewPageAsync().Result;57 logger.Info($"{this.Name}: Initiated PuppeteerBrowser");58 }59 object browserLock = new object();60 public PuppeteerSharp.Page Page()61 {62 return this.page;63 }64 public void WarmUp()65 {66 logger.Debug($"{this.Name}: Warming up");67 this.page.GoToAsync("https://www.google.com").Wait();68 }69 internal void RecreatedChrome()70 {71 logger.Info($"{this.Name}: Recreating PuppeteerBrowser");72 lock (browserLock)73 {74 this.page.Dispose();75 this.browser.CloseAsync().Wait();76 }77 System.Threading.Thread.Sleep(500);78 Init();79 }80 #region IDisposable Support81 private bool disposedValue = false; // To detect redundant calls82 protected virtual void Dispose(bool disposing)83 {84 logger.Info($"{this.Name}: Disposing PuppeteerBrowser Instance");85 if (!disposedValue)86 {87 if (disposing)88 {89 // TODO: dispose managed state (managed objects).90 }91 logger.Debug($"{this.Name}: Closing PuppeteerBrowser");92 this.browser.CloseAsync().Wait();93 logger.Debug($"{this.Name}: Closed PuppeteerBrowser");94 // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.95 // TODO: set large fields to null.96 disposedValue = true;97 }98 }99 // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.100 ~PuppeteerBrowser()101 {102 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.103 Dispose(false);104 }105 // This code added to correctly implement the disposable pattern.106 public void Dispose()107 {108 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.109 Dispose(true);110 // TODO: uncomment the following line if the finalizer is overridden above.111 GC.SuppressFinalize(this);112 }113 #endregion114 }115}...
PuppeteerSharpRepoSpecs.cs
Source:PuppeteerSharpRepoSpecs.cs
...15 {16 Headless = true17 }).Await();18 };19 Cleanup after = () => Browser.CloseAsync().Await();20 class When_searching_for_the_repo_on_GitHub21 {22 It should_be_the_first_search_result = () =>23 {24 Page page = Browser.NewPageAsync().Await();25 page.GoToAsync("https://github.com/").Await();26 page.QuerySelectorAsync("h1").ShouldHaveContent("Where the world builds software");27 ElementHandle input = page.QuerySelectorAsync("input.header-search-input").Await();28 if (input.IsHidden()) page.ClickAsync(".octicon-three-bars").Await();29 page.TypeAsync("input.header-search-input", "Puppeteer Sharp").Await();30 page.Keyboard.PressAsync("Enter").Await();31 page.WaitForNavigationAsync().Await();32 ElementHandle[] repositories = page.QuerySelectorAllAsync(".repo-list-item").Await();33 repositories.Length.ShouldBeGreaterThan(0);...
PuppeteerSharpRepoTests.cs
Source:PuppeteerSharpRepoTests.cs
...17 {18 Headless = true19 });20 }21 [TestCleanup]22 public async Task TestCleanup()23 {24 await Browser.CloseAsync();25 }26 [TestMethod]27 public async Task Should_be_first_search_result_on_GitHub()28 {29 var page = await Browser.NewPageAsync();30 await page.GoToAsync("https://github.com/");31 var h1 = await page.QuerySelectorAsync("h1");32 await h1.ShouldHaveContentAsync("Where the world builds software");33 var input = await page.QuerySelectorAsync("input.header-search-input");34 if (await input.IsHiddenAsync()) await page.ClickAsync(".octicon-three-bars");35 await page.TypeAsync("input.header-search-input", "Puppeteer Sharp");36 await page.Keyboard.PressAsync("Enter");...
BaseUIFixture.cs
Source:BaseUIFixture.cs
1using FluentAssertions;2using Microsoft.Extensions.Hosting;3using Newtonsoft.Json;4using Newtonsoft.Json.Linq;5using NUnit.Framework;6using NUnit.Framework.Internal;7using PuppeteerSharp;8using PuppeteerSharp.Input;9using System;10using System.Collections.Generic;11using System.IO;12using System.Linq;13using System.Text;14using System.Threading;15using System.Threading.Tasks;16namespace E13.Common.Nunit.UI17{18 public abstract class BaseUIFixture : LaunchSettingsFixture, IDisposable19 {20 protected static readonly bool InMemory = Environment.GetEnvironmentVariable("InMemory").DefaultParse(false);21 protected static readonly string TestGoodUserName = Environment.GetEnvironmentVariable("TestGoodUserName");22 protected static readonly string TestDisabledUserName = Environment.GetEnvironmentVariable("TestDisabledUserName");23 protected static readonly string TestInvalidUserName = Environment.GetEnvironmentVariable("TestInvalidUserName");24 protected static readonly string TestPassword = Environment.GetEnvironmentVariable("TestPassword");25 private readonly CancellationTokenSource CancelSource;26 private readonly Func<IHostBuilder> BuilderFunc;27 private readonly int PageWidth;28 private readonly int PageHeight;29 protected Browser Browser { get; set; }30 protected Page Page { get; set; }31 protected BaseUIFixture(int w, int h, Func<IHostBuilder> builderFunc)32 {33 PageWidth = w;34 PageHeight = h;35 BuilderFunc = builderFunc;36 CancelSource = new CancellationTokenSource();37 }38 [SetUp]39 public void SetUp()40 {41 // print out the directory the screens are saved to for ease of navigating locally42 WriteLine($"Screens Directory: {PageExtensions.ScreensDirectory}");43 }44 [OneTimeSetUp]45 public void OneTimeSetUp()46 {47 // Init the InMemory server if required48 49 if (InMemory)50 BuilderFunc().RunConsoleAsync(CancelSource.Token);51 new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision).Wait();52 Browser = Puppeteer.LaunchAsync(new LaunchOptions53 {54 Headless = true,55 IgnoreHTTPSErrors = true,56 }).Result;57 Page = Browser.NewPageAsync().Result;58 Page.SetViewportAsync(new ViewPortOptions { Width = PageWidth, Height = PageHeight });59 }60 protected static void WriteLine(string s) 61 => TestContext.WriteLine(s);62 #region IDisposable Support63 private bool disposedValue = false; // To detect redundant calls64 protected virtual void Dispose(bool disposing)65 {66 if (!disposedValue)67 {68 if (disposing)69 {70 Browser.CloseAsync().Wait();71 CancelSource.Cancel();72 CancelSource.Dispose();73 }74 // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.75 // TODO: set large fields to null.76 disposedValue = true;77 }78 }79 [OneTimeTearDown]80 // This code added to correctly implement the disposable pattern.81 public void Dispose()82 {83 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.84 Dispose(true);85 GC.SuppressFinalize(this);86 }87 #endregion88 }89}...
PdfGenerator.cs
Source:PdfGenerator.cs
1using System;2using System.Threading.Tasks;3using Microsoft.Extensions.Logging;4using PuppeteerSharp;5namespace EMBC.PDFGenerator.Utilities.PdfGenerator6{7 public interface IPdfGenerator : IDisposable8 {9 public Task<byte[]> Generate(string source);10 }11 public class PdfGenerator : IPdfGenerator, IDisposable12 {13 private readonly RevisionInfo puppeteerInfo;14 private readonly ILogger<PdfGenerator> logger;15 private readonly Browser browser;16 private bool disposedValue;17 public PdfGenerator(RevisionInfo puppeteerInfo, ILogger<PdfGenerator> logger)18 {19 this.puppeteerInfo = puppeteerInfo;20 this.logger = logger;21 logger.LogInformation("Using Puppeteer from {0}", puppeteerInfo.ExecutablePath);22 browser = Puppeteer.LaunchAsync(new LaunchOptions23 {24 Headless = true,25 ExecutablePath = puppeteerInfo.ExecutablePath,26 Args = new[] { "--disable-dev-shm-usage", "--no-sandbox", "--no-first-run", "--disable-gpu", "--disable-setuid-sandbox", "--disable-accelerated-2d-canvas", "--no-zygote" },27 Timeout = TimeSpan.FromSeconds(10).Milliseconds,28 LogProcess = true,29 DumpIO = true,30 }).GetAwaiter().GetResult();31 logger.LogInformation("Created Puppeteer browser version {0}", browser.GetVersionAsync().GetAwaiter().GetResult());32 }33 public async Task<byte[]> Generate(string source)34 {35 using var page = await browser.NewPageAsync();36 logger.LogInformation("Created Puppeteer page");37 await page.SetContentAsync(source);38 var content = await page.PdfDataAsync(new PdfOptions { PrintBackground = true });39 logger.LogInformation("Generated pdf with size {0}", content.Length);40 await page.CloseAsync();41 return content;42 }43 protected virtual void Dispose(bool disposing)44 {45 if (!disposedValue)46 {47 if (disposing)48 {49 // TODO: dispose managed state (managed objects)50 browser.Dispose();51 logger.LogInformation("Browser closed");52 }53 // TODO: free unmanaged resources (unmanaged objects) and override finalizer54 // TODO: set large fields to null55 disposedValue = true;56 }57 }58 // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources59 // ~PdfGenerator()60 // {61 // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method62 // Dispose(disposing: false);63 // }64 public void Dispose()65 {66 // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method67 Dispose(disposing: true);68 GC.SuppressFinalize(this);69 }70 }71}...
AbstractScraper.cs
Source:AbstractScraper.cs
1using PuppeteerSharp;2using System;3using System.Collections.Generic;4using System.Threading.Tasks;5namespace KenshiScraper6{7 abstract class AbstractScraper : IDisposable8 {9 protected Browser browser;10 protected Page page;11 public async Task DownloadChromium()12 {13 var fetcher = new BrowserFetcher();14 await fetcher.DownloadAsync();15 }16 public abstract Task<IEnumerable<Article>> ScrapeAsync(IEnumerable<Article> articles);17 protected async Task Initialize()18 {19 if (browser == null || page == null)20 {21 await DownloadChromium();22 browser = await Puppeteer.LaunchAsync(new LaunchOptions() { Headless = false });23 var pages = await browser.PagesAsync();24 page = pages[0];25 }26 }27 protected async Task<string> ExtractPropertyAsync(ElementHandle handle, string nodeProperty)28 {29 return await handle.EvaluateFunctionAsync<string>($"t => t.{nodeProperty}");30 }31 protected async Task<string> ExtractPropertyAsync(ElementHandle handle, string cssSelector, string nodeProperty)32 {33 var queried = await handle.QuerySelectorAsync(cssSelector);34 return await ExtractPropertyAsync(queried, nodeProperty);35 }36 #region IDisposable Support37 private bool disposedValue = false; // To detect redundant calls38 protected virtual void Dispose(bool disposing)39 {40 if (!disposedValue)41 {42 if (disposing)43 {44 // TODO: dispose managed state (managed objects).45 }46 page.Dispose();47 browser.Dispose();48 disposedValue = true;49 }50 }51 // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.52 // ~AbstractScraper()53 // {54 // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.55 // Dispose(false);56 // }57 // This code added to correctly implement the disposable pattern.58 public void Dispose()59 {60 // Do not change this code. Put cleanup code in Dispose(bool disposing) above.61 Dispose(true);62 // TODO: uncomment the following line if the finalizer is overridden above.63 // GC.SuppressFinalize(this);64 }65 #endregion66 }67}...
BasicScreenshot.cs
Source:BasicScreenshot.cs
...27 await page.ScreenshotAsync($"{screenshotDir}/tmp_screenshot.png").ConfigureAwait(false);28 Console.WriteLine("Screenshot grabbed!");29 return $"{screenshotDir}/tmp_screenshot.png";30 }31 public async Task Cleanup(Page page)32 {33 if (page == null) throw new ArgumentNullException(nameof(page), "No chromium instance passed");34 await page.CloseAsync().ConfigureAwait(false);35 if (File.Exists($"{screenshotDir}/tmp_screenshot.png")) File.Delete($"{screenshotDir}/tmp_screenshot.png");36 Console.WriteLine("Temporary files wiped. Page destroyed.");37 }38 }39}...
Cleanup
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 {6 static async Task Main(string[] args)7 {
Cleanup
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 await page.ScreenshotAsync("google.png");15 }16 }17 }18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 {25 static async Task Main(string[] args)26 {27 {28 };29 using (var browser = await Puppeteer.LaunchAsync(options))30 {31 using (var page = await browser.NewPageAsync())32 {33 await page.ScreenshotAsync("google.png");34 }35 }36 }37 }38}39using System;40using System.Threading.Tasks;41using PuppeteerSharp;42{43 {44 static async Task Main(string[] args)45 {46 {47 };48 using (var browser = await Puppeteer.LaunchAsync(options))49 {50 using (var page = await browser.NewPageAsync())51 {52 await page.ScreenshotAsync("google.png");53 }54 }55 }56 }57}58using System;59using System.Threading.Tasks;60using PuppeteerSharp;61{62 {63 static async Task Main(string[] args)64 {65 {66 };67 using (var browser = await Puppeteer.LaunchAsync(options))68 {69 using (var page = await browser.NewPageAsync())70 {71 await page.GoToAsync("https
Cleanup
Using AI Code Generation
1var browser = await Puppeteer.LaunchAsync(new LaunchOptions2 {3 Args = new string[] { "--no-sandbox" }4 });5 var page = await browser.NewPageAsync();6 await page.ScreenshotAsync("google.png");7 await page.CleanupAsync();8var browser = await Puppeteer.LaunchAsync(new LaunchOptions9 {10 Args = new string[] { "--no-sandbox" }11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14 await page.CloseAsync();15var browser = await Puppeteer.LaunchAsync(new LaunchOptions16 {17 Args = new string[] { "--no-sandbox" }18 });19 var page = await browser.NewPageAsync();20 await page.ScreenshotAsync("google.png");21 await browser.CloseAsync();22var browser = await Puppeteer.LaunchAsync(new LaunchOptions23 {24 Args = new string[] { "--no-sandbox" }25 });26 var page = await browser.NewPageAsync();27 await page.ScreenshotAsync("google.png");28 await browser.DisposeAsync();29var browser = await Puppeteer.LaunchAsync(new LaunchOptions30 {31 Args = new string[] { "--no-sandbox" }32 });33 var page = await browser.NewPageAsync();34 await page.ScreenshotAsync("google.png");35 await page.DisposeAsync();36var browserFetcher = new BrowserFetcher();
Cleanup
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.CleanupAsync();3var page = await browser.NewPageAsync();4await page.CleanupAsync();5var page = await browser.NewPageAsync();6await page.CleanupAsync();7var page = await browser.NewPageAsync();8await page.CleanupAsync();9var page = await browser.NewPageAsync();10await page.CleanupAsync();11var page = await browser.NewPageAsync();12await page.CleanupAsync();13var page = await browser.NewPageAsync();14await page.CleanupAsync();15var page = await browser.NewPageAsync();16await page.CleanupAsync();17var page = await browser.NewPageAsync();18await page.CleanupAsync();19var page = await browser.NewPageAsync();20await page.CleanupAsync();21var page = await browser.NewPageAsync();22await page.CleanupAsync();
Cleanup
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.CleanupAsync();3await browser.CloseAsync();4var page = await browser.NewPageAsync();5await page.CleanupAsync();6await browser.CloseAsync();7var page = await browser.NewPageAsync();8await page.CleanupAsync();9await browser.CloseAsync();10var page = await browser.NewPageAsync();11await page.CleanupAsync();12await browser.CloseAsync();13var page = await browser.NewPageAsync();14await page.CleanupAsync();15await browser.CloseAsync();16var page = await browser.NewPageAsync();17await page.CleanupAsync();18await browser.CloseAsync();19var page = await browser.NewPageAsync();20await page.CleanupAsync();21await browser.CloseAsync();22var page = await browser.NewPageAsync();23await page.CleanupAsync();24await browser.CloseAsync();25var page = await browser.NewPageAsync();26await page.CleanupAsync();27await browser.CloseAsync();28var page = await browser.NewPageAsync();29await page.CleanupAsync();
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!!