使用HtmlAgilityPack(Linq)解析html表

时间:2018-08-20 04:13:14

标签: linq html-table html-agility-pack

这是表格结构:

<table class="tb-stock tb-option">
<tr>
    <th class="bgc2">col1</th>
    <th class="bgc2">col2</th>
    <th class="bgc2">col3</th>
</tr>
<tr class="alt-row">
    <th class="">2018/1/29</th>
    <td class="">0.11</td>
    <td class=" b-b">0.50</td>
</tr>
<tr class="alt-row">
    <th class="">2018/1/30</th>
    <td class="">0.22</td>
    <td class=" b-b">0.55</td>
</tr>
</table>

我想获取“ tr”下的所有元素(包括“ th”和“ td”)

我如何使用linq实现这一目标?

问题位于“ ..tr.Elements(“ td | th”)..“

代码:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(ms, Encoding.UTF8);

List<List<string>> table = 
doc.DocumentNode.SelectSingleNode("//table[@class='tb-stock tb-option']")
                .Descendants("tr")
                .Skip(1)
                .Where(tr => tr.Elements("th").Count() >= 1)
                .Select(tr => tr.Elements("td|th").Select(td => td.InnerText).ToList())
                .ToList();

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码提取我在本地测试的td或th元素的内部文本,输出为:

2018/1/29
0.11
0.50
2018/1/30
0.22
0.55

您可以过滤以下行中的元素:

// both td and th
.Where(node => "td|th".Contains(node.Name))
// only td
.Where(node => "td".Contains(node.Name))

工作代码是:

HtmlDocument doc = new HtmlDocument();
doc.Load("test.html", Encoding.UTF8);

List<string> table =
doc.DocumentNode.SelectSingleNode("//table[@class='tb-stock tb-option']")
    .Descendants("tr")
    .Skip(1)
    .Where(tr => tr.Elements("th").Count() >= 1)
    .SelectMany(tr => tr.ChildNodes)
    .Where(node => "td|th".Contains(node.Name))
    .Select(node => node.InnerText)
    .ToList();

foreach (var str in table)
{
    Console.WriteLine(str);
}