HtmlAgilityPack解析文本块

时间:2012-11-17 08:36:42

标签: c# html-agility-pack

我正在制作一个小型网络分析工具,需要以某种方式提取给定网址上包含超过X个字词数量的所有文本块。

我目前使用的方法是:

        public string getAllText(string _html)
    {
        string _allText = "";
        try
        {
            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(_html);


            var root = document.DocumentNode;
            var sb = new StringBuilder();
            foreach (var node in root.DescendantNodesAndSelf())
            {
                if (!node.HasChildNodes)
                {
                    string text = node.InnerText;
                    if (!string.IsNullOrEmpty(text))
                        sb.AppendLine(text.Trim());
                }
            }

            _allText = sb.ToString();

        }
        catch (Exception)
        {
        }

        _allText = System.Web.HttpUtility.HtmlDecode(_allText);

        return _allText;
    }

这里的问题是我得到所有文本都返回,即使它是一个经文,带有3个单词的页脚文本等等。

我想分析页面上的实际内容,所以我的想法是以某种方式解析可能是内容的文本(即超过X个单词的文本块)

有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:1)

嗯,第一种方法可以是使用string.Split函数在每个node.InnerText值上进行简单的字数统计分析:

string[] words;
words = text.Split((string[]) null, StringSplitOptions.RemoveEmptyEntries);

并仅附加words.Length大于3的文字。

另请参阅this question answer了解原始文本收集中的一些技巧。

相关问题