【问题标题】:How to Retrieve Specific table from HTML FILE in c#?如何从 C# 中的 HTML 文件中检索特定表?
【发布时间】:2020-03-19 19:54:05
【问题描述】:

我有一个包含许多表格的 HTML 文件,但我想从文件中访问特定表格(不是所有表格)。 那么我该怎么做呢? 代码如下所示,所有表都没有 id

`<table border=1>
<tr><td>VI not loadable</td><td>0</td></tr>
<tr><td>Test not loadable</td><td>0</td></tr>
<tr><td>Test not runnable</td><td>0</td></tr>
<tr><td>Test error out</td><td>0</td></tr>
</table>`

【问题讨论】:

    标签: c# web-scraping html-parsing


    【解决方案1】:

    每个表都应该有一个 Id 或可以从其他表中识别出来的东西,如果是这样,您可以通过 jquery 获取它。例如:

     <table class="table table-striped" id="tbl1">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
      </tr>
    </tbody>
    

    然后像这样得到它:

    var table = $('#tbl1').html();
    

    如果没有,您可以通过文件中的优先级找到它。例如,您可以像这样访问第二张表:

    var table = $('table:nth-child(2)')
    

    或者在 C# 中,这可能会有所帮助:

    HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]")
    foreach (var cell in table.SelectNodes(".//tr/td")) 
    {
         string someVariable = cell.InnerText
    }
    

    【讨论】:

    • 问题是文件不包含任何 id 或类:
    • 我认为最好的解决方案是按优先级获取目标表,否则当表没有任何指示符时,请解释如何识别您想要的选项,以便我可以帮助您实施一个好的解决方案。跨度>
    • 我正在使用此代码获取一个表,但它返回文件中的所有表。我想检索一个特定的表:foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) { ///This is the table. foreach (HtmlNode row in table.SelectNodes("tr")) { Console.WriteLine(row.OuterHtml); foreach (HtmlNode cell in row.SelectNodes("th|td")) { ///This the cell. Console.WriteLine(html); } } }
    • 我很高兴它成功了,让我开心并将其标记为正确答案:)
    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2013-08-25
    • 2016-01-31
    相关资源
    最近更新 更多