【问题标题】:How to get the count of tables in an html file with C# and html-agility-pack如何使用 C# 和 html-agility-pack 获取 html 文件中的表数
【发布时间】:2013-04-26 23:17:45
【问题描述】:

这是一个新手问题,所以请提供工作代码。

如何使用 C# 和 html-agility-pack 计算 html 文件中的表?

(我需要根据表的数量从 html 文件中的特定表中获取值。然后我将对检索到的值进行一些数学运算。)

为方便起见,这是一个包含三个表的示例文件:

<html>
<head>
<title>Tables</title>
</head>
<body>
<table border="1">
  <tr>
    <th>Name</th>
    <th>Phone</th>
    <th>City</th>
    <th>Number</th>
  </tr>
  <tr>
    <td>Scott</td>
    <td>555-2345</td>
    <td>Chicago</td>
    <td>42</td>
  </tr>
  <tr>
    <td>Bill</td>
    <td>555-1243</td>
    <td>Detroit</td>
    <td>23</td>
  </tr>
  <tr>
    <td>Ted</td>
    <td>555-3567</td>
    <td>Columbus</td>
    <td>9</td>
  </tr>
</table>
<p></p>
<table border="1">
  <tr>
    <th>Name</th>
    <th>Year</th>
  </tr>
  <tr>
    <td>Abraham</td>
    <td>1865</td>
  </tr>
  <tr>
    <td>Martin</td>
    <td>1968</td>
  </tr>
  <tr>
    <td>John</td>
    <td>1963</td>
  </tr>
</table>
<p></p>
<table border="1">
  <tr>
    <th>Animal</th>
    <th>Location</th>
    <th>Number</th>
  </tr>
  <tr>
    <td>Tiger</td>
    <td>Jungle</td>
    <td>8</td>
  </tr>
  <tr>
    <td>Hippo</td>
    <td>River</td>
    <td>4</td>
  </tr>
  <tr>
    <td>Camel</td>
    <td>Desert</td>
    <td>3</td>
  </tr>
</table>
</body>
</html>

如果您愿意,请展示如何将结果发送到新的文本文件。

谢谢!

【问题讨论】:

    标签: c# html html-parsing html-agility-pack


    【解决方案1】:

    我认为这可以作为一个起点

    var doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(html);
    
    var tables = doc.DocumentNode.Descendants("table");
    int tablesCount = tables.Count();
    
    foreach (var table in tables)
    {
        var rows = table.Descendants("tr")
                        .Select(tr => tr.Descendants("td").Select(td => td.InnerText).ToList())
                        .ToList();
    
        foreach(var row in rows)
            Console.WriteLine(String.Join(",", row));
    }
    

    【讨论】:

    • I4V,我无法让您的代码正常工作。我想了解它。我用我的html文件的地址替换了括号中的“html”并运行了代码。所发生的只是黑屏迅速闪过一次。没有其他的。我添加了“Console.ReadLine();”在您提供并运行的代码中的最后一个“}”之后。黑屏现在保持打开状态,光标在它的开头闪烁。不返回任何值。我看不到“int tablesCount = tables.Count();”如何可以输出,我不确定代码的其余部分应该做什么。请澄清。
    • I replaced the "html" in brackets with the address to my html file and ran the code。不,LoadHtml 需要一个 html string,如果你想从 file 加载你应该使用 Load
    【解决方案2】:

    类似这样的:

    HtmlDocument doc = new HtmlDocument();
    doc.Load(myTestFile);
    
    // get all TABLE elements recursively
    int count = doc.DocumentNode.SelectNodes("//table").Count;
    
    // output to a text file
    File.WriteAllText("output.txt", count.ToString());
    

    【讨论】:

    • Simon,我能够让您的代码为我工作。由于对 C# 不太熟悉,因此需要做一些工作,但我学到了一些东西。谢谢!
    猜你喜欢
    • 2013-08-21
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多