HtmlAgilityPack - How to set custom encoding when loading pages

核能气质少年 提交于 2019-12-01 12:29:53

问题


Is it possible to set custom encoding when loading pages with the method below?

HtmlWeb hwWeb = new HtmlWeb();
HtmlDocument hd = hwWeb.load("myurl");

I want to set encoding to "iso-8859-9".

I use C# 4.0 and WPF.

Edit: The question has been answered on MSDN.


回答1:


I suppose you could try overriding the encoding in the HtmlWeb object.

Try this:

var web = new HtmlWeb
{
    AutoDetectEncoding = false,
    OverrideEncoding = myEncoding,
};
var doc = web.Load(myUrl);

Note: It appears that the OverrideEncoding property was added to HTML agility pack in revision 76610 so it is not available in the current release v1.4 (66017). The next best thing to do would be to read the page manually with the encodings overridden.




回答2:


var document = new HtmlDocument();

using (var client = new WebClient())
{
    using (var stream = client.OpenRead(url))
    {
        var reader = new StreamReader(stream, Encoding.GetEncoding("iso-8859-9"));
        var html = reader.ReadToEnd();
        document.LoadHtml(html);
    }
}

This is a simple version of the solution answered here (for some reasons it got deleted)




回答3:


A decent answer is over here which handles auto-detecting the encoding as well as some other nifty features:

C# and HtmlAgilityPack encoding problem



来源:https://stackoverflow.com/questions/7883693/htmlagilitypack-how-to-set-custom-encoding-when-loading-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!