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

我试图将从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); } 

您正在将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); }