使用XPath查找具体内容

时间:2012-02-09 02:30:46

标签: ruby xpath nokogiri

我有一张桌子,表格中有:

<table cellpadding="1" cellspacing="0" width="100%" border="0">
<tr>

<td colspan="7" class="csoGreen" width="120%"><b class="white">Accounts and Payment   Methods</b></td>
</tr>
<input type="hidden" name="pageNum" value=""/>
<input type="hidden" name="reload" value=""/>

<tr class="tableCellHeader">
<td nowrap="nowrap"><b></b></td>
<td nowrap="nowrap"><b>Account Number
<br/><br/><span id="accountToggle" style="color:#ff0000"></span></b></td>
<td nowrap="nowrap"><b><center>Amount Due</center></b></td>
<td nowrap="nowrap"><b><center>Due Date</center></b></td>

<td nowrap="nowrap"><b>Enter/Edit<br/>Payment<br/>Amount<span class="red">*</span></b></td>
<td nowrap="nowrap"><b>Enter/Edit<br/>Payment<br/>Date<span class="red">*</span></b></td>
<td nowrap="nowrap"><b>Please select a Payment Method<span class="red">*</span></b></td>

现在我写了这个并且它有效:

account_overview_tag.xpath("//td[contains(descendant::center, 'Amount Due')]")

但是,我想测试它是一个特定的td例如

account_overview_tag.xpath("//td[2][contains(descendant::center, 'Amount Due')]")

如何让我的XPATH表达式工作?

1 个答案:

答案 0 :(得分:1)

包含到期金额<td>实际上是第三个孩子,所以:

account_overview_tag.xpath("//td[2][contains(descendant::center, 'Amount Due')]")

会给你nil表示没有匹配。但是:

account_overview_tag.xpath("//td[3][contains(descendant::center, 'Amount Due')]")

将为您提供您正在寻找的节点。通过在XPath中包含<tr>,您可以更具体一点:

//tr[@class="tableCellHeader"]/td[3][contains(descendant::center, "Amount Due")]