PuppeteerSharp开源地址:PuppeteerSharp
PuppeteerSharp官网地址:PuppeteerSharp官网
PuppeteerSharp实现整网页截图:
//初始化浏览器 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, }); using (var page = await browser.NewPageAsync()) { // 允许运行js await page.SetJavaScriptEnabledAsync(true); await page.GoToAsync("https://www.baidu.com"); await page.ScreenshotAsync("E://test50x50.png", new ScreenshotOptions() { FullPage = false, Type = ScreenshotType.Png }); } browser.Dispose();
注:执行
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
可能需要科学上网
实现指定元素截图:
//初始化浏览器 await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, }); using (var page = await browser.NewPageAsync()) { // 允许运行js await page.SetJavaScriptEnabledAsync(true); //初始化时指定窗口大小 await page.SetViewportAsync(new ViewPortOptions { Width = 500, Height = 500 }); await page.GoToAsync("http://127.0.0.1:8848/%E6%BE%B3%E9%97%A8%E9%81%93%E8%B7%AF%E8%B7%AF%E6%B3%81-%E5%89%8D%E7%AB%AF/index.html"); //获取指定元素 var element = await page.MainFrame.QuerySelectorAsync(".box_left_gao"); //截图 await element.ScreenshotAsync("E://test50x50.png", new ScreenshotOptions() { FullPage = false, Type = ScreenshotType.Png }); } browser.Dispose();
评论区