使用此HTML代码:
<div class="one">
.....
</div>
<div class="one">
.....
</div>
<div class="one">
.....
</div>
<div class="one">
.....
</div>
如何与Nokogiri一起选择班级为1的第二或第三div?
您可以使用 Ruby 将大型结果集缩减为特定项:
page.css('div.one')[1,2] # Two items starting at index 1 (2nd item)
page.css('div.one')[1..2] # Items with indices between 1 and 2, inclusive
因为 Ruby 索引从零开始,所以你必须注意你想要的项目。
或者,您可以使用 CSS 选择器查找第 n项:
# Second and third items from the set, jQuery-style
page.css('div.one:eq(2),div.one:eq(3)')
# Second and third children, CSS3-style
page.css('div.one:nth-child(2),div.one:nth-child(3)')
或者,您可以使用 XPath 获取特定匹配项:
# Second and third children
page.xpath("//div[@class='one'][position()=2 or position()=3]")
# Second and third items in the result set
page.xpath("(//div[@class='one'])[position()=2 or position()=3]")
对于CSS和XPath替代方案,请注意:
- 编号从 1 开始,而不是 0
您可以改用
at_css
和at_xpath
来获取第一个这样的匹配元素,而不是 NodeSet。# A NodeSet with a single element in it: page.css('div.one:eq(2)') # The second div element page.at_css('div.one:eq(2)')
最后,请注意,如果使用 XPath 按索引选择单个元素,则可以使用较短的格式:
# First div.one seen that is the second child of its parent
page.at_xpath('//div[@class="one"][2]')
# Second div.one in the entire document
page.at_xpath('(//div[@class="one"])[2]')
page.css('div.one')[1] # For the second
page.css('div.one')[2] # For the third