简体   繁体   English

使用 HtmlAgilityPack C# 从 html 文档中获取特定表

[英]Get specific table from html document with HtmlAgilityPack C#

I have html document with two tables.我有带有两个表格的 html 文档。 For example:例如:

<html>
    <body>
        <p>This is where first table starts</p>
        <table>
            <tr>
                <th>head</th>
                <th>head1</th>
            </tr>
            <tr>
                <td>data</td>
                <td>data1</td>
            </tr>
        </table>
        <p>This is where second table starts</p>
        <table>
            <tr>
                <th>head</th>
                <th>head1</th>
            </tr>
            <tr>
                <td>data</td>
                <td>data1</td>
            </tr>
        </table>
    </body>
</html>

And i want to parse first and second but separatly I will explain:我想解析第一个和第二个,但我将分别解释:

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(@richTextBox1.Text);
if(comboBox_tables.Text.Equals("Table1"))
{
   DataTable dt = new DataTable();
   dt.Columns.Add("id", typeof(string));
   dt.Columns.Add("inserted_at", typeof(string));
   dt.Columns.Add("DisplayName", typeof(string));
   HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
            foreach (var row in doc.DocumentNode.SelectNodes("//tr"))
                {
                    var nodes = row.SelectNodes("td");
                    if (nodes != null)
                    {

                        var id = nodes[0].InnerText;
                        var inserted_at = nodes[1].InnerText;
                        var DisplayName = nodes[2].InnerText;

                        dt.Rows.Add(id, inserted_at, DisplayName);
                    }
    dataGridView1.DataSource = dt;

I'm trying to select first table with //table[1].我正在尝试使用//table [1] select 第一个表。 But it's always takes both tables.但它总是需要两张桌子。 How can i select the first table for if(table1) and the second for else if(table2)?我怎么能 select 第一个表为 if(table1) 而第二个为 else if(table2)?

You are selecting the table[1] , but not doing anything with the return value.您正在选择table[1] ,但没有对返回值做任何事情。 Use the table variable to select all tr nodes.使用table变量 select 所有tr节点。

HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
foreach (var row in table.SelectNodes("//tr"))

.. rest of the code .. rest的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM