PuppeteerSharp (C#)
环境:Win7系统 .net framework 4.6.1
我们在以上环境中,使用PuppeteerSharp,导出PDF时,会出现下面的错误:
PlatformNotSupportedException: 此平台不支持 WebSocket 协议。(Failed to create connection),创建连接失败,本质还是因为平台不支持 WebSocket 协议所致。关于这个问题,也很简单,只要稍加留心,在PuppeteerSharp sdk中已经做了说明,就是LaunchOptions对象中,WebSocketFactory属性的配置说明:
//
// 摘要:
// Optional factory for System.Net.WebSockets.WebSocket implementations. If PuppeteerSharp.LaunchOptions.Transport
// is set this property will be ignored.
//
// 备注:
// If you need to run Puppeteer-Sharp on Windows 7, you can use PuppeteerSharp.LaunchOptions.WebSocketFactory
// to inject https://www.nuget.org/packages/System.Net.WebSockets.Client.Managed/.
备注已经很清楚的告诉我们,如果要想在win7中运行,需要使用PuppeteerSharp.LaunchOptions.WebSocketFactory的配置,而这个配置,需要我们引用一个dll。https://www.nuget.org/packages/System.Net.WebSockets.Client.Managed/ nuget命令工具安装或者可视化工具搜索System.Net.WebSockets.Client.Managed
Install-Package System.Net.WebSockets.Client.Managed -Version 1.0.22
WebSocketFactory的本质是个委托,我们按照委托的签名,通过刚引用的组件,创建对应的方法即可:
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <param name="options"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private static async Task<WebSocket> CreateWebSocket(Uri url, IConnectionOptions options, CancellationToken cancellationToken)
{
var result = new System.Net.WebSockets.Managed.ClientWebSocket();
result.Options.KeepAliveInterval = TimeSpan.Zero;
await result.ConnectAsync(url, cancellationToken).ConfigureAwait(false);
return result;
}
修改LaunchOptions配置
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
{
Headless = false,
WebSocketFactory = CreateWebSocket,
}))
这样在运行,即可!
PuppeteerSharp 系列文章: