HTML Agility Pack在页面上获取所有锚点的href属性
我试图将从HTML文件中提取的链接添加到CheckBoxList
( cbl_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
属性的值。 您所看到的是HtmlNode
的ToString()
值,因为这是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); }