如何选择具有“foo”类的 td?

Onl*_*ere 2 html c# html-table html-agility-pack

我正在使用 HtmlAgilityPack 并且我想从带有 class 的 td 中选择值title。我需要标签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;
Run Code Online (Sandbox Code Playgroud)

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

感谢您的建议。

<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>
Run Code Online (Sandbox Code Playgroud)

Pat*_*Pat 5

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

//td[@class='title']/a
Run Code Online (Sandbox Code Playgroud)

它应该为您提供具有“标题”类的元素中的所有元素。然后您将遍历该 NodeCollection 并调用 node.InnerText 属性。

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

W3Schools的教程/资源非常适合快速入门。