【问题标题】:Getting links from table via HtmlAgilityPack通过 HtmlAgilityPack 从表中获取链接
【发布时间】:2013-05-23 22:05:03
【问题描述】:

我有简单的 html 表格:

<table>
  <tr>
    <td>
      <a href="http://someurl_1.com">item name1</a>
    </td>
    <td>
      Value 1
    </td>
  </tr>
  <tr>
    <td>
      <a href="http://someurl_2.com">item name2</a>
    </td>
    <td>
      Value 2
    </td>
  </tr>
</table>

现在我需要将该表中的数据作为列表>(或字符串[][])

为了得到它,我使用:

        List<List<string>>
            table = doc.DocumentNode.SelectSingleNode("//table")
                    .Descendants("tr")
                    .Skip(1)
                    .Where(tr => tr.Elements("td").Count() > 1)
                    .Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList())
                    .ToList();

它,成功地让我只有字符串数据,所以结果我有

table[0][0] -> item name1
table[0][1] -> value 1
table[1][0] -> item name2
table[1][1] -> value 2

但我在那个数组中没有 url。

我怎样才能得到它的表值,所以结果我需要有:

table[0][0] -> http://someurl_1.com
table[0][1] -> item name1
table[0][2] -> value 1
table[1][0]-> http://someurl_2.com
table[1][1] -> item name2
table[1][2] -> value 2

任何帮助不胜感激!谢谢

【问题讨论】:

    标签: c# html parsing html-parsing html-agility-pack


    【解决方案1】:

    我建议对每个单元格使用 xpath 并将它们的数据映射到您的数组。

    例如第二项的xpath是/html/body/table/tbody/tr[2]/td[1]/a

      var doc = new HtmlAgilityPack.HtmlDocument();
      doc.LoadHtml(htmlText);
      var nodes = doc.DocumentNode.SelectNodes("/html/body/table/tbody/tr[2]/td[1]/a");
    

    会给你&lt;a href="http://someurl_2.com"&gt;item name2&lt;/a&gt;作为一个节点,你可以用它来获取url或文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      相关资源
      最近更新 更多