HtmlAgilityPack多元素

时间:2016-02-15 16:38:07

标签: c# regex html-agility-pack

我有一个包含多个div的html文档

示例:

<div class="element">
    <div class="title">
        <a href="127.0.0.1" title="Test>Test</a>
    </div>
</div>

现在我使用此代码提取标题元素。

List<string> items = new List<string>();
var nodes = Web.DocumentNode.SelectNodes("//*[@title]");
if (nodes != null)
{
   foreach (var node in nodes)
   {
       foreach (var attribute in node.Attributes)
           if (attribute.Name == "title")
               items.Add(attribute.Value);
   }
}

我不知道如何调整我的代码来提取href和title元素 在同一时间。

每个div应该是一个包含标签作为属性的对象。

public class CheckBoxListItem
{
    public string Text { get; set; }
    public string Href { get; set; }
}

2 个答案:

答案 0 :(得分:1)

您可以使用以下xpath查询仅检索带有title和href的标记:

//a[@title and @href]

你可以像这样使用你的代码:

List<CheckBoxListItem> items = new List<CheckBoxListItem>();
var nodes = Web.DocumentNode.SelectNodes("//a[@title and @href]");
if (nodes != null)
{
   foreach (var node in nodes)
   {
      items.Add(new CheckBoxListItem()
      {
        Text = node.Attributes["title"].Value,
        Href = node.Attributes["href"].Value
      });
   }
}

答案 1 :(得分:1)

我经常将ScrapySharp的包与HtmlAgilityPack一起用于css选择。

(为ScrapySharp.Extensions添加一个using语句,以便您可以使用CssSelect方法。)

using HtmlAgilityPack;
using ScrapySharp.Extensions;

在你的情况下,我会这样做:

HtmlWeb w = new HtmlWeb();

var htmlDoc = w.Load("myUrl");
var titles = htmlDoc.DocumentNode.CssSelect(".title");
foreach (var title in titles)
{
    string href = string.Empty;
    var anchor = title.CssSelect("a").FirstOrDefault();

    if (anchor != null)
    {
        href = anchor.GetAttributeValue("href");
    }
}
相关问题