首页 > 其他分享 >Playwright支持DevProtocol的api了

Playwright支持DevProtocol的api了

时间:2023-03-17 23:56:44浏览次数:58  
标签:Playwright await frameId api var DevProtocol Page

之前文章Playwright简单试用中提过,Playwright .net api中并不支持直接调用DevProtocol的api, 今天试了一下,发现已经支持了。便看看能不能实现比较常用的获取资源树和资源(一般是图片)的功能,这个功能我在之前的文章中用puppeteer实现过,便参考着改了一下,还是比较容易的:

var client = await page.Context.NewCDPSessionAsync(page);

var resource = await client.SendAsync("Page.getResourceTree");
var frameId  = resource.Value.GetProperty("frameTree").GetProperty("frame").GetProperty("id").GetString();

await client.SendAsync("Page.enable");		//需要发送Page.enable指令
var content = await client.SendAsync("Page.getResourceContent", new Dictionary<string, object>()
{
	{ "frameId", frameId },
	{ "url", "https://www.baidu.com/img/flexible/logo/pc/[email protected]" }
});

var bytes = content.Value.GetProperty("content").GetBytesFromBase64();
await File.WriteAllBytesAsync(@"logo.png", bytes);

一些不方便的地方是:

  • 不支持json path(据说在年底的.net 8中支持),操作json不像node中那么方便,
  • 一些底层的接口还是没有公开,如frameId, 需要用别的方式获取。

不过,在c#的强类型和智能提示加持下,实现了过后,复用还是非常方便的,并且也更方便调试,开发蜘蛛程序更便捷了。支持DevProtocol的api后,功能也更加强大了。

参考文章:

标签:Playwright,await,frameId,api,var,DevProtocol,Page
From: https://www.cnblogs.com/TianFang/p/17228887.html

相关文章