0

我正在尝试解析下表,但不幸的是每个节点似乎都相互嵌套。:( 获取子节点是不可能的,因为它总是给出 count = 1

这真的很有趣,但它正在寻找;例如下一个“tr”作为前一个 tr 的子节点?

你有什么主意吗?

<table width="292px" border="0">
    <tr>
        <td>
        </td>
    </tr>
    <tr>
        <td>
            <table>
                <tr>
                    <td colspan="2" bgcolor="#FBCE9D" align="center" height="40">
                    </td>
                </tr>
                <tr>
                    <td bgcolor="#FFF4D2" height="25" width="60">
                    </td>
                    <td height="25" bgcolor="#e8e8e8">
                    </td>
                </tr>
                <tr>
                    <td bgcolor="#FFF4D2" height="25" width="60">
                    </td>
                    <td height="25" bgcolor="#e8e8e8">
                    </td>
                </tr>
                <tr>
                    <td bgcolor="#FFF4D2" height="25" width="60">
                    </td>
                    <td height="25" bgcolor="#e8e8e8">
                    </td>
                </tr>
                <tr>
                    <td bgcolor="#FFF4D2" height="25" width="60">
                    </td>
                    <td height="25" bgcolor="#e8e8e8">
                    </td> //Here is a missing "</tr>" and I think this one is confusing the agilitypack!
                    <tr>
                        <td bgcolor="#FFF4D2" height="35" colspan="2" align="center">
                        </td>
                    </tr>
            </table>
        </td>
    </tr>
</table>

我的代码是:

var webGet = new HtmlWeb();
var doc = webGet.Load("the url where this table is located");
HtmlNodeCollection tb = doc.DocumentNode.SelectNodes("//table[@width='292px']");
                        var table = tb[0].ChildNodes[1].ChildNodes[0].ChildNodes[0].ChildNodes;
                        for (var na = 0; na < table.Count; na++)
                        { .....do the work.... }

实际上,这段代码以前就像一个魅力一样工作,但他们在里面嵌套了另一个表,ChildNodes[1]因为ChildNodes[1]它永远不会存在ChildNodes[0]

再来一张纸条;Firebug 将“/html/body/table/tbody/tr[2]/td/table/tbody”显示为嵌套表的 XPath,但您可能注意到“tbody”不熟悉 htmlagility,因为它是由浏览器删除缺少的关闭标签 /tr

4

2 回答 2

1

这真的很有趣,但问题是在 Nuget 上实际可用的 HmtlAgility 包!我将其删除并从网上下载(http://htmlagilitypack.codeplex.com/)。它现在正在工作!

于 2012-04-17T11:36:35.387 回答
0

XPATH会在这里帮助你很多。

对于内部表tr节点,您可以在下面尝试

doc.DocumentNode.SelectNodes("//table[@width='292px']/tr/td/table/tr")

如果要遍历td内部表中的节点,则

doc.DocumentNode.SelectNodes("//table[@width='292px']/tr/td/table/tr/td")
于 2012-04-13T07:17:41.260 回答