问题描述
我有一张桌子:
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 匹配文本一张桌子 - Ruby - Nokigiri).如果我使用第一行中的任何词作为匹配词,例如Statement",它就可以正常工作.但是,如果我使用另一行中的单词,例如金额",则它不起作用.
I use the codes suggested in this post (XPath matching text in a table - Ruby - Nokigiri). It works fine if I use any words in the first row as the match word, for example "Statement". But it doesn't work if I use words that in the other row, for example "Amount".
doc = Nokogiri::HTML("#{html}")
doc.xpath('//table[contains(descendant::*, "Statement")]').each do |node|
puts node.text
end
推荐答案
contains()
函数需要一个奇异值作为它的第一个参数.descendant::*
可能会产生多个元素,然后导致函数出现意外行为,例如只考虑产生的第一个元素.
The contains()
function expects a singular value as its first argument. descendant::*
may yield multiple elements then causing the function to behave unexpectedly, such as considering only the first element yielded.
尝试将您的 XPath 更改为:
Try to change your XPath to be:
doc.xpath('//table[descendant::*[contains(., "Amount")]]').each do |node|
puts node.text
end
这篇关于查找包含特定文本的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!