HtmlAgilityPack 抓取页面的乱码处理


利用HtmlAgilityPack抓取页面很方便,但是当页面是gb2312编码时候就会出现乱码,上网查了一下说是默认的获取页面方法不够成熟,具体什么的我也不知道,姑且就认为是不够成熟吧。

HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument htmlDocument = htmlWeb.Load(@url);

 

解决方法如下:

新建一个方法来获取 HtmlDocument,传进来的是抓取页面的地址

       private static HtmlDocument GetHtmlDocument(string url)
        {
            HttpWebRequest httpWebRequest = WebRequest.Create(new Uri(@url)) as HttpWebRequest;
            httpWebRequest.Method = "GET";
            WebResponse webResponse = httpWebRequest.GetResponse();
            Stream stream = webResponse.GetResponseStream();
            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.Load(stream);

            return htmlDocument;
        }

 

根据@无机の剑 的评论,用这个属性就解决了(O(∩_∩)O~):

HtmlWeb htmlWeb = new HtmlWeb(); 
htmlWeb.OverrideEncoding = Encoding.GetEncoding("gb2312");

 

 这样就可以啦!至于后面的使用方法都一样,具体可以参考这个博客,讲的很详细哈 http://www.cnblogs.com/linfei721/archive/2013/05/08/3066697.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM