c# - 如何选择类别为 "foo"的 td ?

标签 c# html html-agility-pack html-table

我正在使用 HtmlAgilityPack,我想从类 title 的 td 中选择值。我需要值 Battlefield 3位于 <a> 内标签。

我尝试了以下操作,只是为了获取正确的 td 元素,但出现异常 object is not set to an instance .

var title = from item in document.DocumentNode.Descendants()
            where item.Name == "td" && item.Attributes["class"].Value == "title"
            select item.InnerHtml;

通过这个小例子,我可能会弄清楚我需要的其余部分。

感谢您的建议。

<tr class="first-in-year">
  <td class="year">2011</td>

  <td class="img"><a href="/battlefield-3/61-27006/"><img src=
  "http://media.giantbomb.com/uploads/6/63038/1700748-bf3_thumb.jpg" alt=""></a></td>

  <td class="title">
    <a href="/battlefield-3/61-27006/">Battlefield 3</a>

    <p class="deck">Battlefield 3 is DICE's next installment in the franchise and
    will be on PC, PS3 and Xbox 360. The game will feature jets, prone, a
    single-player and co-op campaign, and 64-player multiplayer (on PC). It's due out
    in Fall of 2011.</p>
  </td>
</tr>

最佳答案

尝试将 XPath 选择器与类或其他属性说明符一起使用。

//td[@class='title']/a

它应该为您提供具有“title”类的元素中的所有元素。然后,您将迭代该 NodeCollection 并调用 node.InnerText 属性。

  var nodes = doc.DocumentNode.SelectNodes("//td[@class='title']/a");
  foreach(HtmlNode node in nodes)
  {
     string title = node.InnerText;
  }

教程/资源位于 W3Schools非常适合快速提升。

关于c# - 如何选择类别为 "foo"的 td ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5970966/

相关文章:

html - IE 8 忽略 div 中的边距

php - 我无法通过使用 PDO、PHP、SQL、HTML 的查询来更新某些记录

c# - jquery改变后如何获取HtmlDocument? (HtmlAgilityPack)

c# - HTMLAgilityPack 链接和描述提取

c# - 如何在 C# 代码中创建 Razor Page Urls?

c# - 在 Linux 上使用 C#/Mono 处理外部媒体

Javascript 库无需在脚本标签中使用导入

C#,解析HTML页面,使用HTML Agility Pack

c# - ReSharper 好奇号 : "Parameter is only used for precondition check(s)."

c# - 打印时将行设置为在顶部重复 - 打开 XML 和 Excel