HTML Agility Pack在页面上获取所有锚点的href属性 [英] HTML Agility Pack get all anchors' href attributes on page

查看:382
本文介绍了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属性的值.您看到的是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);
}

I am trying to add links extracted from an HTML file to a CheckBoxList (cbl_items).

It works so far but instead of the link, the item's name is displayed as HtmlAgilityPack.HtmlNode. I tried using DocumentElement instead of Node but it said that it does not exist or similar.

How can I get the URL to be displayed instead of HtmlAgilityPack.HtmlNode?

This is what I've tried so far:

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);
}

解决方案

You are adding the HtmlNode object to the CheckBoxList and not the value of the href attribute. What you are seeing is the HtmlNode's ToString() value since that's the best that the CheckBoxList can do to display that object.

Instead, you can use GetAttributeValue(string attribute, string defaultValue) to retrieve the href attribute's value.

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);
}

这篇关于HTML Agility Pack在页面上获取所有锚点的href属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆