htmlagilitypack-删除脚本和样式?我使用以下方法从html中提取文本:publicstringgetAllText(string_html){string_allText="";尝试{HtmlAgilityPack.HtmlDocument文档=newHtmlAgilityPack.HtmlDocument();文档.LoadHtml(_html);varroot=document.DocumentNode;varsb=newStringBuilder();foreach(varnodeinroot.DescendantNodesAndSelf()){if(!node.HasChildNodes){stringtext=node.InnerText;如果(!string.IsNullOrEmpty(text))sb.AppendLine(text.Trim());}}_allText=sb.ToString();}赶上(异常){}_allText=System.Web.HttpUtility.HtmlDecode(_allText);返回_allText;}问题是我还得到了脚本和样式标签。我怎样才能排除它们?HtmlAgilityPack.HtmlDocumentdoc=newHtmlAgilityPack.HtmlDocument();doc.LoadHtml(html);doc.DocumentNode.Descendants().Where(n=>n.Name=="script"||n.Name=="style").ToList().ForEach(n=>n.Remove());您可以使用HtmlDocument类来执行此操作:HtmlDocumentdoc=newHtmlDocument();doc.LoadHtml(输入);doc.DocumentNode.SelectNodes("//style|//script").ToList().ForEach(n=>n.Remove());一些很好的答案,System.Linq很方便!对于非基于Linq的方式:以上是C#学习教程:htmlagilitypack-removescriptsandstyles?如果分享的所有内容对你有用,需要了解更多C#学习教程,希望你多多关注——.HtmlNodeCollectionNodes=webDocument.DocumentNode.SelectNodes("//脚本");//确保不是Null:if(Nodes==null)returnwebDocument;//移除所有节点:foreach(HtmlNodenodeinNodes)node.Remove();返回网络文档;}这个文件整理自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
