【问题标题】:Encoding error when using HTML Agility Pack使用 HTML Agility Pack 时出现编码错误
【发布时间】:2010-03-10 03:54:10
【问题描述】:

我正在尝试解析一个 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");
                }
            }
        }

任何帮助将不胜感激:)

【问题讨论】:

  • 您没有告诉我们确切的错误信息,也没有提供任何方法让我们重现此信息(即示例 html)。但从理论上讲,这样的事情应该可以工作......

标签: c# html parsing html-agility-pack


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多