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

use*_*921 20 c# html-agility-pack

我正在尝试将从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);
}
Run Code Online (Sandbox Code Playgroud)

Rya*_*rle 24

您要将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);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果没有节点匹配,不要忘记允许`SelectNodes`(令人难以置信地)返回`null`这一事实. (3认同)