我正在使用HtmlAgilityPack。是否有一行代码可以获取html的所有内部文本,例如删除所有html标签和脚本?
像这样:
document.DocumentNode.InnerText
请注意,这将返回 <script>
标签的文本内容。
为了解决这个问题,你可以像这样删除所有的 <script>
标签:
foreach(var script in doc.DocumentNode.Descendants("script").ToArray())
script.Remove();
foreach(var style in doc.DocumentNode.Descendants("style").ToArray())
style.Remove();
HtmlNodeCollection[i].InnerText
来获取它的文本。 HtmlDocument hDoc;
HtmlNodeCollection nodeCollection;
public void InitInstance(string htmlCode) {
hDoc.LoadHtml(htmlCode);
nodeCollection = new HtmlNodeCollection();
}
private void GetAllNodesInnerTextByTagName(HtmlNode node, string tagName) {
if (null == node.ChildNodes) {
return ;
} else {
HtmlNodeCollection nCollection = node.SelectNodes( tagName );
if( null != nCollection ) {
for( int i=0; i<nCollection.Count; i++) {
nodeCollection.Add( nCollection[i]);
nCollection[i].Remove();
}
}
nCollection=node.ChildNodes;
if(null != nCollection) {
for(int i=0;i<nCollection.Count; i++) {
GetAllNodesInnerTextByTagName( nCollection[i] , tagName );
}
}
}
ToArray()
来在单独的副本上进行迭代的原因。 - SLaks