.NET 利用PuppeteerSharp生成页面图片
程序员文章站
2022-07-02 08:02:21
安装 NuGet 程序包 - PuppeteerSharp Install-Package PuppeteerSharp 创建个控制台程序。 新方法 class Program { static void Main(string[] args) { Console.WriteLine("Hello ......
安装 nuget 程序包 - puppeteersharp
install-package puppeteersharp
创建个控制台程序。
新方法
class program { static void main(string[] args) { console.writeline("hello world!"); createhtmlimg(); console.readline(); } static async void createhtmlimg() { // 首次 执行程序 会先下载一个 chrome 程序 , 下载完成后下次就不用下载。 await new browserfetcher().downloadasync(browserfetcher.defaultrevision); using (browser browser = await puppeteer.launchasync(new launchoptions { headless = true })) { using (var page = await browser.newpageasync()) { //设置浏览器的页面大小 await page.setviewportasync(new viewportoptions { width = 1024, height = 768 }); string url = "https://www.cnblogs.com/"; await page.gotoasync(url); // 可执行javasctipt //var seven = await page.evaluatefunctionasync<int>("()=> 4 + 3"); //var someobject = await page.evaluatefunctionasync<dynamic>("(value) => ({a: value})", 5); var html = await page.getcontentasync(); var sourcefile = ""; var memorystream = new memorystream(encoding.default.getbytes(html)); var sr = new streamreader(memorystream); sourcefile = sr.readtoend(); //针对源代码进行分析 sr.close(); //将页面保存为图片 using (var stream = await page.screenshotstreamasync(new screenshotoptions { fullpage = false })) { byte[] srcbuf = new byte[stream.length]; stream.read(srcbuf, 0, srcbuf.length); stream.seek(0, seekorigin.begin); using (filestream fs = new filestream(@"d:\垃圾\"+ datetime.now.tostring("yyyymmddhhmmsssss") +".png",filemode.create, fileaccess.write)) { fs.write(srcbuf, 0, srcbuf.length); } } //将页面保存为图片 //await page.screenshotasync(@"d:\垃圾\"+ datetime.now.tostring("yyyymmddhhmmsssss") +".png", //new screenshotoptions() { fullpage = true, type = screenshottype.png }; } } } }
首次执行会比较慢,要下载 chrome ,330m
上一篇: C#获取指定目录下的指定文件