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