htmlagilitypack提取电子邮件

时间:2014-07-10 14:11:32

标签: c# .net html-agility-pack

我正在执行以下代码以使用htmlagilitypack提取页面的所有链接。当我输入网址https://htmlagilitypack.codeplex.com/时,我不会收到任何错误,代码也能正常运行。 URL也被提取并显示良好。但是,如果我输入任何其他URL,如https://htmlagilitypack.codeplex.com/discussions/12447,那么我得到以下错误"对象引用未设置为对象的实例"。我在这一行中遇到错误

OutputLabel.Text += counter + ". " + aTag.InnerHtml + " - " + 
                    aTag.Attributes["href"].Value + "\t" + "<br />"; 

请帮帮我。这对你来说可能是一个小错误,但请不要将其标记为否定。

var getHtmlWeb = new HtmlWeb();
var document = getHtmlWeb.Load(InputTextBox.Text);
var aTags = document.DocumentNode.SelectNodes("//a");
int counter = 1;

if (aTags != null)
{
    foreach (var aTag in aTags)
    {
        OutputLabel.Text += counter + ". " + aTag.InnerHtml + " - " + 
                            aTag.Attributes["href"].Value + "\t" + "<br />"; 
        counter++;
    }
}

1 个答案:

答案 0 :(得分:4)

看起来某些锚点没有 href 属性。例如。在给定的页面中有锚:

<a name="post40566"></a>

因此,aTag.Attributes["href"]会返回null,并且当您尝试获取此属性值时会出现异常。您可以更改XPath以仅选择具有此属性的锚点:

document.DocumentNode.SelectNodes("//a[@href]");

或者在访问其值之前验证属性是否存在:

if (aTag.Attributes["href"] != null)
    // ...

第三个选项是GetAttributeValue方法的使用,并提供一些默认值,可以显示缺少的属性:

aTag.GetAttributeValue("href", "N/A")
相关问题