项目地址:https://github.com/hardkoded/puppeteer-sharp
Puppeteer Sharp is a .NET port of the official Node.JS Puppeteer API.
As Puppeteer-Sharp is a NetStandard 2.0 library, the minimum platform versions are .NET Framework 4.6.1 and .NET Core 2.0. Read more.
The minimum Windows versions supporting the WebSocket library are Windows 8 and Windows Server 2012. Read more.
If you need to run Puppeteer-Sharp on Windows 7 you can use System.Net.WebSockets.Client.Managed through the LaunchOptions.WebSocketFactory property.
If you have issues running Chrome on Linux, the Puppeteer repo has a great troubleshooting guide.
X-server is required on Linux.
使用说明
Take screenshots
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }); var page = await browser.NewPageAsync(); await page.GoToAsync("http://www.google.com"); await page.ScreenshotAsync(outputFile);
You can also change the view port before generating the screenshot
await page.SetViewportAsync(new ViewPortOptions { Width = 500, Height = 500 });
Generate PDF files
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }); var page = await browser.NewPageAsync(); await page.GoToAsync("http://www.google.com"); await page.PdfAsync(outputFile);
Inject HTML
using(var page = await browser.NewPageAsync()) { await page.SetContentAsync("<div>My Receipt</div>"); var result = await page.GetContentAsync(); await page.PdfAsync(outputFile); SaveHtmlToDB(result); }
Evaluate Javascript
using (var page = await browser.NewPageAsync()) { var seven = await page.EvaluateExpressionAsync<int>("4 + 3"); var someObject = await page.EvaluateFunctionAsync<dynamic>("(value) => ({a: value})", 5); Console.WriteLine(someObject.a); }
Wait For Selector
using (var page = await browser.NewPageAsync()) { await page.GoToAsync("http://www.spapage.com"); await page.WaitForSelectorAsync("div.main-content") await page.PdfAsync(outputFile)); }
谢谢浏览!