我有一张 table :
html ='
<table cellpadding="1" cellspacing="0" width="100%" border="0">
<tr>
<td colspan="9" class="csoGreen"><b class="white">Bill Statement Detail</b></td>
</tr>
<tr style="background-color: #D8E4F6;vertical-align: top;">
<td nowrap="nowrap"><b>Bill Date</b></td>
<td nowrap="nowrap"><b>Bill Amount</b></td>
<td nowrap="nowrap"><b>Bill Due Date</b></td>
<td nowrap="nowrap"><b>Bill (PDF)</b></td>
</tr>
</table>
'
我使用这篇文章中建议的代码 ( XPath matching text in a table - Ruby - Nokigiri)。如果我使用第一行中的任何单词作为匹配词,例如“语句”,它就可以正常工作。但是,如果我使用另一行中的单词,例如“金额”,它就不起作用。
doc = Nokogiri::HTML("#{html}")
doc.xpath('//table[contains(descendant::*, "Statement")]').each do |node|
puts node.text
end
请您参考如下方法:
contains()函数需要一个奇异值作为它的第一个参数。 descendant::*可能会产生多个元素,然后导致函数出现意外行为,例如只考虑产生的第一个元素。
尝试将您的 XPath 更改为:
doc.xpath('//table[descendant::*[contains(., "Amount")]]').each do |node|
puts node.text
end


