How to use Dispose method of PuppeteerSharp.Page class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.Dispose

WebScraper.cs

Source:WebScraper.cs Github

copy

Full Screen

...133 private async Task<Bitmap> SnapshotBitmapAsync()134 {135 var data = await m_page.ScreenshotStreamAsync();136 var image = new Bitmap(data);137 data.Dispose();138 return image;139 }140 /// <summary>141 /// Simulates key presses on page.142 /// </summary>143 /// <param name="text">Text to send to page.</param>144 public void SendKeys(string text)145 {146 SendKeysAsync(text).Wait();147 }148 private async Task SendKeysAsync(string text)149 {150 await m_page.Keyboard.TypeAsync(text);151 }152 /// <summary>153 /// Simulates moving the mouse on the page.154 ///155 /// Note: this does not move the system mouse.156 /// </summary>157 /// <param name="x">X coordinates to move mouse to.</param>158 /// <param name="y">Y coordinates to move mouse to.</param>159 public void MoveMouse(decimal x, decimal y)160 {161 MoveMouseAsync(x, y).Wait();162 }163 private async Task MoveMouseAsync(decimal x, decimal y)164 {165 await m_page.Mouse.MoveAsync(x, y);166 m_MouseX = x;167 m_MouseY = y;168 }169 /// <summary>170 /// Simulates a mouse click on page.171 /// </summary>172 /// <param name="button">Mouse button to simulate.</param>173 public void MouseClick(MouseButton button)174 {175 MouseClickAsync(button).Wait();176 }177 private async Task MouseClickAsync(MouseButton button)178 {179 await m_page.Mouse.ClickAsync(m_MouseX, m_MouseY, new ClickOptions{ Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });180 }181 /// <summary>182 /// Simulates a mouse up event on page.183 /// </summary>184 /// <param name="button">Mouse button to simulate.</param>185 public void MouseUp(MouseButton button)186 {187 MouseUpAsync(button).Wait();188 189 }190 private async Task MouseUpAsync(MouseButton button)191 {192 await m_page.Mouse.UpAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });193 }194 /// <summary>195 /// Simulates a mouse down event on page.196 /// </summary>197 /// <param name="button">Mouse button to simulate.</param>198 public void MouseDown(MouseButton button)199 {200 MouseDownAsync(button).Wait();201 }202 private async Task MouseDownAsync(MouseButton button)203 {204 await m_page.Mouse.DownAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });205 }206 /// <summary>207 /// Simulates a touch tap on a page.208 /// </summary>209 /// <param name="target">Javascript selector for element to tap on.</param>210 public void TapScreen(string target)211 {212 TapScreenAsync(target).Wait();213 }214 private async Task TapScreenAsync(string target)215 {216 await m_page.TapAsync(target);217 }218 /// <summary>219 /// Generates a pdf of the page.220 /// </summary>221 /// <returns>Stream containing the pdf data.</returns>222 public Stream CreatePdf()223 {224 var data = CreatePdfAsync();225 data.Wait();226 return data.Result;227 }228 private async Task<Stream> CreatePdfAsync()229 {230 return await m_page.PdfStreamAsync();231 }232 /// <summary>233 /// Waits for expression to be to be true.234 /// </summary>235 /// <param name="expression">Expression to wait on.</param>236 public void WaitOnScript(string expression)237 {238 WaitOnScriptAsync(expression).Wait();239 }240 private async Task WaitOnScriptAsync(string expression)241 {242 await m_page.WaitForExpressionAsync(expression);243 }244 /// <summary>245 /// Selects element on page to have focus.246 /// </summary>247 /// <param name="target">Javascript selector to make have focus.</param>248 public void Focus(string target)249 {250 FocusAsync(target).Wait();251 }252 private async Task FocusAsync(string target)253 {254 await m_page.FocusAsync(target);255 }256 /// <summary>257 /// Clicks on target element on page.258 /// </summary>259 /// <param name="target">Javascript selector of element to click on.</param>260 public void Click(string target)261 {262 ClickAsync(target).Wait();263 }264 private async Task ClickAsync(string target)265 {266 await m_page.ClickAsync(target);267 }268 /// <summary>269 /// Html content of page. Useful for scraping the html directly.270 /// </summary>271 public string Content272 {273 get274 {275 var data = m_page.GetContentAsync();276 data.Wait();277 return data.Result;278 }279 set280 {281 var data = m_page.SetContentAsync(value);282 data.Wait();283 }284 }285 /// <inheritdoc />286 /// <summary>287 /// Dispose method.288 /// This will close out chromium session.289 /// </summary>290 public void Dispose()291 {292 m_browser?.Dispose();293 m_page?.Dispose();294 }295 }296}...

Full Screen

Full Screen

SaveWebPage.xaml.cs

Source:SaveWebPage.xaml.cs Github

copy

Full Screen

...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}");107108 pdfOptions.Width = $"{width}px";109 pdfOptions.Height = $"{height}px";110111 pdfOptions.HeaderTemplate = ""; //页眉文本112 pdfOptions.Landscape = false; //纸张方向 false-垂直 true-水平113 pdfOptions.MarginOptions = new PuppeteerSharp.Media.MarginOptions() { Bottom = "0px", Left = "0px", Right = "0px", Top = "0px" }; //纸张边距,需要设置带单位的值,默认值是None114 pdfOptions.Scale = 1m; //PDF缩放,从0-1115 pdfOptions.PrintBackground = true;116117 var fileName = Environment.CurrentDirectory + $"\\download\\{await page.GetTitleAsync()}.pdf";118119 if (System.IO.File.Exists(fileName))120 {121 fileName = fileName.Replace(".pdf", $"{DateTime.Now.ToString("ffff")}.pdf");122 }123124 //保存PDF125 await page.PdfAsync(fileName, pdfOptions);126 EMessageBox.Show($"{fileName}保存成功");127128 //在最后记得关闭浏览器及释放资源129 browser.Disconnect();130 browser.Dispose();131 }132 catch(Exception ex)133 {134 EMessageBox.Show(ex.Message);135 }136 }137 }138} ...

Full Screen

Full Screen

Form1.cs

Source:Form1.cs Github

copy

Full Screen

...79 //dispose browser80 if (browser != null)81 {82 await browser.CloseAsync();83 browser.Dispose();84 }85 }86 }87}...

Full Screen

Full Screen

PuppeteerBrowser.cs

Source:PuppeteerBrowser.cs Github

copy

Full Screen

...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}...

Full Screen

Full Screen

Crawler.cs

Source:Crawler.cs Github

copy

Full Screen

...66 if (response?.Ok ?? false)67 doc.LoadHtml(await page.GetContentAsync());68 else69 {70 this.Dispose();71 Exceptions.BadOrNoResponseException badResponseException;72 if (response == null)73 badResponseException = new("There is no response from server. Please check your connection.");74 else 75 badResponseException = new(response.StatusText);76 throw badResponseException;77 }78 await ResolvePlaces(token);79 }80 private Task ResolvePlaces(CancellationToken token)81 {82 while(true && !token.IsCancellationRequested)83 {84 if (isFirstPage)85 {86 var match = Regex.Match(page.Url, _UrlRegex);87 var lat = match.Groups["lat"].Value;88 var lon = match.Groups["lon"].Value;89 if (double.TryParse(lat, out var tempLat) && double.TryParse(lon, out var tempLon))90 {91 sourceLat = tempLat;92 sourceLon = tempLon;93 }94 isFirstPage = false;95 }96 var names = doc.DocumentNode.SelectNodes("//h3[contains(@class, 'section-result-title')]");97 var results = doc.DocumentNode.SelectNodes("//*[@id='pane']/div/div[1]/div/div/div[4]/div[1]/div[contains(@class, 'section-result')]");98 for (var i = 0; i < results.Count; i++)99 {100 }101 }102 if(token.IsCancellationRequested)103 Dispose();104 return Task.CompletedTask;105 }106#pragma warning disable CA1816 // Dispose methods should call SuppressFinalize107 public void Dispose()108#pragma warning restore CA1816 // Dispose methods should call SuppressFinalize109 {110 browser.Dispose();111 }112}...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...50 }51 finally52 {53 if(browser != null)54 await browser.DisposeAsync();55 if (AppConfig.ol != null)56 {57 AppConfig.ol.Close();58 AppConfig.ol.Dispose();59 }60 }61 }62 }63}...

Full Screen

Full Screen

BrowserService.cs

Source:BrowserService.cs Github

copy

Full Screen

...25 Console.WriteLine("ERROR: reCAPTCHA");26 }27 public async Task<string> GetHtml()28 => await _currentPage.GetContentAsync();29 public void Dispose() 30 => _browser?.Dispose();31 }32}...

Full Screen

Full Screen

PuppeteerDocumentGenerator.cs

Source:PuppeteerDocumentGenerator.cs Github

copy

Full Screen

...26 Top = "1.5cm",27 Bottom = "1.5cm"28 },29 });30 browser.Dispose();31 return pdfData;32 }33 }34 }35}...

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))2{3 var page = await browser.NewPageAsync();4 await page.ScreenshotAsync("google.png");5}6var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });7var page = await browser.NewPageAsync();8await page.ScreenshotAsync("google.png");9await browser.CloseAsync();10using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))11{12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");14}15var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });16var page = await browser.NewPageAsync();17await page.ScreenshotAsync("google.png");18await browser.CloseAsync();

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))9 using (var page = await browser.NewPageAsync())10 {11 Console.WriteLine("Page title: {0}", await page.GetTitleAsync());12 }13 }14}

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5 static async Task Main(string[] args)6 {7 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);8 var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });9 var page = await browser.NewPageAsync();10 Console.WriteLine("Page loaded successfully");11 await page.WaitForSelectorAsync("input[name='q']");12 await page.TypeAsync("input[name='q']", "Hello World!");13 await page.ClickAsync("input[value='Google Search']");14 await page.WaitForNavigationAsync();15 Console.WriteLine("Page loaded successfully");16 await page.CloseAsync();17 await browser.CloseAsync();18 }19}20using System;21using System.Threading.Tasks;22using PuppeteerSharp;23{24 static async Task Main(string[] args)25 {26 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);27 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))28 {29 var page = await browser.NewPageAsync();30 Console.WriteLine("Page loaded successfully");31 await page.WaitForSelectorAsync("input[name='q']");32 await page.TypeAsync("input[name='q']", "Hello World!");33 await page.ClickAsync("input[value='Google Search']");34 await page.WaitForNavigationAsync();35 Console.WriteLine("Page loaded successfully");36 }37 }38}39using System;40using System.Threading.Tasks;41using PuppeteerSharp;42{43 static async Task Main(string[] args)44 {45 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);46 using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))47 {48 using (var page = await browser.NewPageAsync())49 {50 Console.WriteLine("Page loaded successfully");51 await page.WaitForSelectorAsync("input[name='q']");52 await page.TypeAsync("input[name

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

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 Args = new string[] { "--no-sandbox" }11 });12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("google.png");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 LaunchOptions26 {27 Args = new string[] { "--no-sandbox" }28 });29 var page = await browser.NewPageAsync();30 await page.ScreenshotAsync("google.png");31 await browser.DisposeAsync();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 LaunchOptions43 {44 Args = new string[] { "--no-sandbox" }45 });46 var page = await browser.NewPageAsync();47 await page.ScreenshotAsync("google.png");48 browser.Dispose();49 }50 }51}

Full Screen

Full Screen

Dispose

Using AI Code Generation

copy

Full Screen

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 page.Dispose();13 await browser.CloseAsync();14 }15 }16}17page.CloseAsync();18await browser.CloseAsync();19page.Dispose();20await browser.CloseAsync();

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in Page

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful