【问题标题】:HtmlAgilityPack Error Handling - catching exceptionHtmlAgilityPack 错误处理 - 捕获异常
【发布时间】:2014-05-15 18:22:29
【问题描述】:

我正在尝试确定如何捕获异常我得到的是Object reference not set to an instance of an object.

有没有更好的方法来捕捉异常并向用户展示异常的原因?

       baseUrl = "my url....";
        try
        {
            HtmlWeb hw = new HtmlWeb();
            HtmlDocument docSRC = hw.Load(baseUrl);

            //if (docSRC.DocumentNode.SelectNodes("//img/@src").Count > 0)
            //{

            //}

            foreach (HtmlNode link in docSRC.DocumentNode.SelectNodes("//img/@src"))
            {
                HtmlAttribute att = link.Attributes["src"];
                srcTags.Add(att.Value);

            }
        }
        catch (Exception ex)
        {
            //catch reason for exception....
        }

【问题讨论】:

  • 我希望 HtmlAgilityPack 如果找不到元素就返回 null 。这比预先检查元素是否存在或抛出异常要容易得多。

标签: c# error-handling html-agility-pack


【解决方案1】:

我想不出任何其他方法来处理异常。但是,如果您能首先避免异常,那就更好了。

查看发布的代码sn-p,当link 没有src 属性时,可能会抛出NullReferenceException(这部分att.Value 将抛出异常,因为attnull在这种情况下)。

您可以使用GetAttributeValue() 方法来避免异常,例如:

//here when the attribute not found, the 2nd parameter will be returned 
//(empty string in this case)
var src =  link.GetAttributeValue("src", "");

【讨论】:

  • 1+ 给了我想法......我在 foreach 循环行 foreach (HtmlNode link in docSRC.DocumentNode.SelectNodes("//img/@src")) 上遇到了错误
【解决方案2】:

这是我能够解决的方法:

            if (docSRC.DocumentNode.SelectNodes("//img/@src") != null)
            {
                foreach (HtmlNode link in docSRC.DocumentNode.SelectNodes("//img/@src"))
                {
                    HtmlAttribute att = link.Attributes["src"];
                    srcTags.Add(att.Value);

                }
            }

希望这对其他人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2010-12-11
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多