0

我正在尝试使用从这个实际站点找到的一些代码来解析 html 文档,但我不断收到解析错误

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

        // There are various options, set as needed
        htmlDoc.OptionFixNestedTags = true;

        // filePath is a path to a file containing the html
        htmlDoc.Load(@"C:\Documents and Settings\Mine\My Documents\Random.html");

        // Use:  htmlDoc.LoadXML(xmlString);  to load from a string

        // ParseErrors is an ArrayList containing any errors from the Load statement
        if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count > 0)
        {
            // Handle any parse errors as required
            MessageBox.Show("Oh no");
        }
        else
        {

            if (htmlDoc.DocumentNode != null)
            {
                HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//head");

                if (bodyNode != null)
                {
                    MessageBox.Show("Hello");
                }
            }
        }

任何帮助,将不胜感激 :)

4

1 回答 1

0

在野外,HTML 很可能是不合规的、不合规的和不验证的。只有 XHTML 或非常简单的 HTML 不会填充 ParseErrors。我注意到 HTML Agility Pack 相当健壮,即使生成了 ParseErrors,仍然可以从大多数 HTML 源构建一个不错的 DOM 树。删除 else,让 else 块正常执行。

如果它没有构建 DOM 树,那么您应该调查生成的 ParseError(s)。如果它只构建了部分树,请尝试在节点上递归、打印或消息框以查看 DOM 树的哪些部分已构建或未构建。您可能不需要整棵树。

于 2010-03-09T19:54:10.220 回答