HTML AgilityPack 笔记查找 Header

HTML AgilityPack Note Finding Header

我正在尝试从网站提取数据。

并且无法提取一些 Header 详细信息。我的代码只是跳过了 headers 它是我试图提取的“<h4 class”。

不同的浏览器包含不同的数据。

例如。

    <section class="results-list">
      <header>
        <h3>U.S. House</h3>
      </header>

      <section class="results-group">
        <header>
          <h4 class="district">Florida 1st congressional district</h4>
        </header>
        <div class="container">
          <div class="row clearfix">



<article class="results fifty">

  <header>
    <h4>Democrat primary</h4>
  </header>

  <section class="results-table">
    <table>
      <tr class="header results-table-row">
        <th class="vote-percent">Percent</th>
        <th class="candidate">Candidate</th>
        <th class="vote-count">Votes</th>
        <th class="winning">Winner</th>
      </tr>

        <tr>
          <td class="vote-percent">55%</td>
          <td class="candidate">Jennifer Zimmerman</td>
          <td class="vote-count">13090</td>
          <td class="winning">WINNER</td>
        </tr>

    </table>
  </section>
</article>

这是我的代码。

        foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
        {
            var temp = table.InnerHtml.ToString();

            foreach (HtmlNode row in table.SelectNodes("tr"))
            {
                ResultsListBox.Items.Add(row.InnerText.ToString());

                foreach (HtmlNode cell in row.SelectNodes("th|td"))
                {
                    ResultsListBox.Items.Add(cell.InnerText.ToString());
                    Console.WriteLine("cell: " + cell.InnerText);
                }
            }
        }

假设在页面中只有一个 header 是 h4 具有 class 属性的元素,您可以尝试以下 XPath 查询:

var queryHeader = "//section/header/h4[@class]";
var header = doc.DocumentNode.SelectSingleNode(queryHeader);
Console.WriteLine("header: " + header.InnerText);