HTML Agility Pack 获取页面上所有锚点的 href 属性

21

我正在尝试将从HTML文件中提取的链接添加到CheckBoxListcbl_items)中。

目前它可以运行,但是显示的项目名称是 HtmlAgilityPack.HtmlNode 而不是链接。 我尝试使用 DocumentElement 替代 Node,但是它显示不存在或类似。

如何使 URL 被显示而不是 HtmlAgilityPack.HtmlNode?

这是我迄今为止尝试过的:

HtmlWeb hw = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(tb_url.Text);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
  cbl_items.Items.Add(link);
}
1个回答

26

您正在将HtmlNode对象添加到CheckBoxList中,而不是href属性的值。您看到的是HtmlNodeToString()值,因为这是CheckBoxList可以显示该对象的最佳方式。

相反,您可以使用GetAttributeValue(string attribute, string defaultValue)来检索href属性的值。

HtmlWeb hw = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(tb_url.Text);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
    // Get the value of the HREF attribute
    string hrefValue = link.GetAttributeValue( "href", string.Empty );
    cbl_items.Items.Add(hrefValue);
}

4
不要忘记考虑到SelectNodes会在没有匹配节点的情况下(令人难以置信地)返回null - T.J. Crowder
现在有HtmlDocument.OptionEmptyCollection,当设置为true时,SelectNodes将返回一个空集合而不是null。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接