Iterate with all elements and get text?

2019-08-01 06:47发布

问题:

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.