【问题标题】:Find a table containing specific text查找包含特定文本的表格
【发布时间】:2014-06-19 07:59:51
【问题描述】:

我有一张桌子:

 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

【问题讨论】:

  • 注意:Nokogiri::HTML("#{html}")Nokogiri::HTML(html) 相同(在这种情况下),也与Nokogiri.HTML(html) 相同

标签: ruby xpath nokogiri


【解决方案1】:

contains() 函数需要一个奇异值作为其第一个参数。 descendant::* 可能会产生多个元素,然后导致函数出现意外行为,例如只考虑产生的第一个元素。

尝试将您的 XPath 更改为:

doc.xpath('//table[descendant::*[contains(., "Amount")]]').each do |node|
    puts node.text
end

【讨论】:

  • 感谢您的回答和解释。现在可以了。
猜你喜欢
  • 1970-01-01
  • 2020-12-24
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2012-05-22
  • 2023-02-21
  • 2017-07-03
相关资源
最近更新 更多