HTML AgilityPack 注释查找标头



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

并且在提取一些标题详细信息时遇到问题。 我的代码只是跳过标题 这是我试图拉出的"<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);
}
}
}

假设页面中只有一个标题是具有class属性h4元素,则可以尝试以下 XPath 查询:

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

最新更新