安装 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