前言
如何将网页生成预览图?
要实现这个功能,可以用WebBrowser组件模拟浏览器,或者使用系统浏览器访问网页,再进行截图操作。
但是,这样需要编写大量的控制代码。
工欲善其事,必先利其器!
利用Playwright提供的强大API,可以轻松实现将网页生成预览图。
Screenshot
实现起来非常简单,直接上代码:
static async Task Main(string[] args)
{var playwright = await Playwright.CreateAsync();await using var browser = await playwright.Chromium.LaunchAsync();var page = await browser.NewPageAsync();await page.GotoAsync("https://cn.bing.com/search?q=intext%3A%22%E8%AF%B7%E5%85%B3%E6%B3%A8%E6%88%91%E7%9A%84%E4%B8%AA%E4%BA%BA%E5%85%AC%E4%BC%97%E5%8F%B7%E2%80%9DMy+IO%E2%80%9C%22");await page.ScreenshotAsync(new PageScreenshotOptions { Path = "screenshot.png", FullPage = true});
}
访问网页,截取成长图,并保存到指定路径。
API详细说明,请参看:https://playwright.dev/dotnet/docs/api/class-page#page-screenshot
Tracing
这个功能可以记录Playwright执行的所有操作流程并截图,对于获取演示素材非常有用。
下面的示例代码,记录了打开bing首页,并且执行搜索操作的全过程:
static async Task Main(string[] args)
{var playwright = await Playwright.CreateAsync();var browser = await playwright.Chromium.LaunchAsync();var context = await browser.NewContextAsync();await context.Tracing.StartAsync(new TracingStartOptions() { Screenshots =true , Snapshots =true });var page = await context.NewPageAsync();await page.GotoAsync("https://cn.bing.com/");// 输入搜索关键字await page.TypeAsync("input[name='q']", "intext:\"请关注我的个人公众号”My IO“\"");var page1 = await page.RunAndWaitForNavigationAsync(async () =>{// 点击搜索await page.ClickAsync("#search_icon");});await context.Tracing.StopAsync(new TracingStopOptions() { Path = "trace.zip" });
}
可以使用Playwright自带的view工具查看整个流程:
playwright show-trace bin\Debug\net5.0\trace.zip
也可以解压trace.zip,拿到所有的截屏图片:
结论
有了Playwright,再也不怕要求实现网页加载后将页面截取成长图片功能了。
如果你觉得这篇文章对你有所启发,请关注我的个人公众号”My IO“