犀利的Html解析器HtmlAgilityPack

HtmlAgilityPack是个开元的html解析器,可以将page source中的javascript&css去掉,当然有时可能会解析不完全。那么如何解决HtmlAgilityPack得到的InnerText中有残留的script、样式的问题,《C#: HtmlAgilityPack extract inner text》

 

实现代码:

foreach(var script in doc.DocumentNode.Descendants("script").ToArray())
    script.Remove();
foreach(var style in doc.DocumentNode.Descendants("style").ToArray())
    style.Remove();

string innerText = doc.DocumentNode.InnerText;

 

加过上边的代码后可能还会有残余的,比方说comment里的script&Css

foreach(var script in doc.DocumentNode.Descendants("script").ToArray())
    script.Remove();
foreach(var style in doc.DocumentNode.Descendants("style").ToArray())
    style.Remove();

foreach (var comment in doc.DocumentNode.SelectNodes("//comment()").ToArray())
    comment.Remove();//删除comment
string innerText = doc.DocumentNode.InnerText;

 

 

同样微软自己的解析器:MSHTML

posted @ 2013-12-24 23:28  MirAcle0909  阅读(246)  评论(0编辑  收藏  举报