选择具有特定属性的元素后的Nokogiri元素

时间:2013-11-05 23:07:55

标签: ruby nokogiri

我已经在这几个小时,我无法取得任何进展。 我不知道如何做以下,我习惯于数组和循环,而不是nokogiri对象。

我想在包含带有id ==“filmography”

的跨度的h2之后立即选择表格元素
<h2><span id ="filmography>...
<table>  # What I want to find
  <tr>
    <td>...

到目前为止,我已经使用了

objects = page.xpath("//h2" | "//table")

有一个nokogiri对象的数组,我测试每个id ==“Filmography”并将使用下一个对象,但返回的元素不按顺序排列,因为它们出现在页面上它们按顺序排列所有h2的然后是所有表格。

我能以某种方式将所有'h2'和'table'作为它们在页面上出现的顺序作为元素对象,并测试子对象'span'的id属性吗?

所有建议都表示赞赏,因为我完全陷入困境。

2 个答案:

答案 0 :(得分:3)

这看起来应该有效:

page.xpath('h2//span[@id="filmography"]').first.next_element

答案 1 :(得分:1)

Nokogiri支持CSS选择器,这使这很容易:

doc.at('span#filmography table').to_html
=> "<table><tr>\n<td>...</td>\n    </tr></table>"

doc.at('#filmography table').to_html
=> "<table><tr>\n<td>...</td>\n    </tr></table>"

at使用CSS或XPath选择器返回第一个匹配的节点。

“NodeSet”等价物是search,它返回一个NodeSet,就像一个数组,但是会强制你在它之后使用first,这只会导致更长的命令: / p>

doc.search('span#filmography table').first.to_html
doc.search('#filmography table').first.to_html

由于span标记包含id参数,因此您可以安全地使用at并仅查找#filmography,因为ID在页面中是唯一的。< / p>

相关问题