解决HtmlAgilityPack中文乱码

Html Agility Pack是用C#写的开源Html Parser。

在抓取163首页(http://www.163.com)代码如下:

	HtmlWeb hw = new HtmlWeb();
	string url = @"http://www.163.com";
	HtmlDocument doc = hw.Load(url);
	doc.Save("mshome.htm");

不过有点问题是抓取的Code乱码了。

通过跟踪代码发现通过修改HtmlWeb.cs 中的第1466行(1.4.0.0版) 文件可以解决这个问题。

方法名为:

private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc, IWebProxy proxy, ICredentials creds)

原始实现源代码:

...
...
Encoding respenc = !string.IsNullOrEmpty(resp.ContentEncoding)
                                   ? Encoding.GetEncoding(resp.ContentEncoding)
                                   : null;
...
...

修改后的代码:

            //Encoding respenc = !string.IsNullOrEmpty(resp.ContentEncoding)
            //                       ? Encoding.GetEncoding(resp.ContentEncoding)
            //                       : null;
            //update By Glen begin
            Encoding respenc;

            if ((resp.ContentEncoding != null) && (resp.ContentEncoding.Length > 0))
            {
                respenc = System.Text.Encoding.GetEncoding(resp.ContentEncoding);
            }
            else if ((resp.CharacterSet != null) && (resp.CharacterSet.Length > 0))//根据Content-Type中获取的charset  
            {
                if (string.Compare(resp.CharacterSet, "ISO-8859-1", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
                    respenc = System.Text.Encoding.GetEncoding("GB2312");
                else
                    respenc = System.Text.Encoding.GetEncoding(resp.CharacterSet);
            }
            else
            {
                respenc = System.Text.Encoding.GetEncoding("GB2312");
            }
            //update By Glen end

重新编译一下,就不会中文乱码了...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值