最近在用.net core寫一個爬蟲抓取網頁上的數據,碰到了網頁編碼是GBK的頁面,抓取的數據都是亂碼,當使用Encoding.GetEncoding(“GBK”)的時候拋出了異常:
'GBK' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
當改用GB2312的時候也拋出了同樣的異常:
'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
從異常上來看是不支持GB2312和GBK。而且提到了需要注冊EncodingProvider的方法。CodePagesEncodingProvider定義在NuGet包“System.Text.Encoding.CodePages”之中。所以我們就需要添加System.Text.Encoding.CodePages的依賴。然后在Project.json中添加
{
"dependencies": { "System.Text.Encoding.CodePages": "4.0.1-rc2-24027" }
}
在代碼中還需要添加Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);如圖:
再次啟動就可以可以使用GB2312