public class PuppeteerSharpHelps { public PuppeteerSharpHelps() { } private static PuppeteerSharp.Browser _browser { get; set; } private async static Task<Browser> Browsers() { try { await slimLock.WaitAsync(); if (_browser == null) { Debug.WriteLine("标识输出"); _browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new string[] { "--no-sandbox", // 沙盒模式 }, }); return _browser; } return _browser; } catch (Exception ex) { throw ex; } finally { slimLock.Release(); } } //异步线程锁 private static SemaphoreSlim slimLock = new SemaphoreSlim(1, 1); private static readonly SemaphoreSlim _mutex = new SemaphoreSlim(10); public static async Task ScreenshotAsync(string loadUrl, string savePath,int width = 0, int height = 0) { try { _browser ??= await Browsers(); await _mutex.WaitAsync(); if (width == 0 || height == 0) { await BrowsersPage(loadUrl, savePath); } else { await BrowsersPage(loadUrl, savePath, width, height); } } catch (Exception ex) { await _browser?.CloseAsync(); GC.Collect(); throw ex; } finally { _mutex.Release(); GC.Collect(); } } private static async Task BrowsersPage(string loadUrl, string savePath) { await Task.Run(async () => { using Page page = await _browser.NewPageAsync(); await page.SetViewportAsync(new ViewPortOptions { Width = 1000, Height = 1000 }); WaitUntilNavigation[] wn = new WaitUntilNavigation[50]; wn[0] = WaitUntilNavigation.Load; await page.GoToAsync(loadUrl, new NavigationOptions() { WaitUntil = wn }); try { await page.ScreenshotAsync(savePath, new ScreenshotOptions() { Type = ScreenshotType.Png }); } catch (Exception ex) { Debug.WriteLine("截图出错:" + ex.Message); } page.Close += async (sender, e) => { var pg = (Page)sender; var size = await pg.Browser.PagesAsync(); if (size.Length <= 1) { await _browser?.CloseAsync(); _browser = null; } }; }); //await page.CloseAsync(); } private static async Task BrowsersPage(string loadUrl, string savePath,int width, int height) { await Task.Run(async () => { using Page page = await _browser.NewPageAsync(); await page.SetViewportAsync(new ViewPortOptions { Width = width, Height = height }); WaitUntilNavigation[] wn = new WaitUntilNavigation[50]; wn[0] = WaitUntilNavigation.Load; await page.GoToAsync(loadUrl, new NavigationOptions() { WaitUntil = wn }); try { //await page.PdfAsync(savePath); await page.ScreenshotAsync(savePath, new ScreenshotOptions() { Type = ScreenshotType.Png }); } catch (Exception ex) { Debug.WriteLine("截图出错:" + ex.Message); } page.Close += async (sender, e) => { var pg = (Page)sender; var size = await pg.Browser.PagesAsync(); if (size.Length <= 1) { await _browser?.CloseAsync(); _browser = null; } }; }); //await page.CloseAsync(); } }
测试代码:
for (int i = 1; i <= 50; i++) { if ((i % 2) == 0) { PuppeteerSharpHelps.ScreenshotAsync("https://www.baidu.com", $"F://test{i}.png", i); } else { PuppeteerSharpHelps.ScreenshotAsync("https://www.csdn.net/", $"F://test{i}.png", i); } }