ruby - XPath 获取两个元素之间的兄弟元素

标签 ruby xpath nokogiri mechanize

使用以下标记,我需要获得中间的 tr

<tr class="H03">
  <td>Artist</td>
  ...
<tr class="row_alternate">
  <td>LIMP</td>
  <td>Orion</td>
  ...
</tr>
<tr class="row_normal">
  <td>SND</td>
  <td>Tender Love</td>
  ...
</tr>
<tr class="report_total">
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  ...
</tr>

那是 <tr class="H03"> 之间的每个 sibling tr和 <tr class="report_total"> .我正在使用 Mechanize 和 nokogiri 进行抓取,因此仅限于他们的 xpath 支持。在查看了各种 StackOverflow 问题后,我的最佳尝试是
page.search('/*/tr[@class="H03"]/following-sibling::tr[count(. | /*/tr[@class="report_total"]/preceding-sibling::tr)=count(/*/tr[@class="report_total"]/preceding-sibling::tr)]')

它返回一个空数组,而且非常复杂,以至于我有限的 xpath fu 完全不知所措!。

最佳答案

您可以尝试以下 xpath :

//tr[@class='H03']/following-sibling::tr[following-sibling::tr[@class='report_total']]

在 xpath 上方全选 <tr>关注 tr[@class='H03'] , 其中 <tr>有以下 sibling tr[@class='report_total']或者换句话说选择 <tr>位于 tr[@class='report_total'] 之前.

关于ruby - XPath 获取两个元素之间的兄弟元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30380987/

相关文章:

xslt - xsl 中的撇号 :format-number

css - 在 Nokogiri 中,我将如何选择具有空类属性的元素?

ruby-on-rails - 为什么我在安装 PaperClip 时得到一个 "undefined method for ` has_attached_file`?

ruby - 为什么 Ruby 有预定义常量 TRUE、FALSE 和 NIL?

ruby - 在 ruby​​ 数组中搜索

ruby-on-rails - 将 RSpec 与 Ruby on Rails 结合使用的国际字符

javascript - 如何使用 javascript 查询 XML 文件中的数据?

html - 提取文本 xpath scrapy

ruby - 如何从字符串中使用 Mechanize 或 Nokogiri 解析表单

ruby-on-rails - 在 ubuntu 服务器上部署 capistrano 时关于 nokogiri 的错误