使用HtmlAgilityPack(Linq)解析html表

html-agility-pack html-table linq

這是表結構:

<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();

一般承認的答案

您可以使用以下代碼提取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);
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow