我正在执行以下代码以使用 htmlagilitypack 提取页面的所有链接。当我输入 URL 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++;
}
}
请您参考如下方法:
看起来有些 anchor 没有href 属性。例如。在给定页面中有 anchor :
<a name="post40566"></a>
因此,aTag.Attributes["href"] 返回 null,当您尝试获取此属性值时出现异常。您可以更改 XPath 以仅选择那些具有此属性的 anchor :
document.DocumentNode.SelectNodes("//a[@href]");
或者在访问它的值之前验证属性是否存在:
if (aTag.Attributes["href"] != null)
// ...
第三个选项是使用 GetAttributeValue 方法并提供一些默认值,该值将显示为缺少的属性:
aTag.GetAttributeValue("href", "N/A")
