Iterate with all elements and get text?

不羁的心 提交于 2019-12-24 07:58:13

问题


I am using the follow code to get all text from a page into a List<string>

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);

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

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

foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("//text()"))
{
    string found = WebUtility.HtmlDecode(node.InnerText.Trim());
    if (found.Length > 2) // removes some unwanted strings
        query[item.Key].Add(found);
}
  • But some html is still going into the string such as </form> is there a better way to narrow this code so I get only the text of each tag and nothing else or I will have to still parse the results to remove <*> tags ?

回答1:


This can be done rather easily using only functions included in the HAP.

HtmlDocument doc = new HtmlWeb().Load("http://www.google.com");
List<string> words = doc.DocumentNode.DescendantNodes()
        .Where(n => n.NodeType == HtmlNodeType.Text
          && !string.IsNullOrWhiteSpace(HtmlEntity.DeEntitize(n.InnerText))
          && n.ParentNode.Name != "style" && n.ParentNode.Name != "script")
        .Select(n => HtmlEntity.DeEntitize(n.InnerText).Trim())
        .Where(s => s.Length > 2).ToList();

The result is a list of words with a length of more than 2 and everything already escaped, so no need for WebUtility.



来源:https://stackoverflow.com/questions/10808099/iterate-with-all-elements-and-get-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!