侧边栏壁纸
博主头像
分享你我博主等级

行动起来,活在当下

  • 累计撰写 108 篇文章
  • 累计创建 13 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

.net core 使用PuppeteerSharp 实现整个网页截图、指定元素截图

管理员
2020-10-20 / 0 评论 / 0 点赞 / 6 阅读 / 5415 字

 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();


0

评论区