遍历所有元素,并得到文本? [英] Iterate with all elements and get text?

查看:197
本文介绍了遍历所有元素,并得到文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在用的是后续code,以得到一个页面的所有文字变成名单,其中,串>

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);
}

  • 但是,一些HTML仍然会到字符串,如&LT; /形式GT; 是 有没有更好的方式来缩小这个code,所以我得到的每一个只有文字 标签并没有别的否则我将不得不结果还是解析到 删除&LT; *?>标记
    • 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 ?
    • 推荐答案

      这是可以做到相当容易地只使用列入HAP功能。

      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();
      

      结果的话有超过2,一切都已经逃脱了长的列表,所以不需要 WebUtility

      这篇关于遍历所有元素,并得到文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆