使用此HTML代码:
<div class="one">
.....
</div>
<div class="one">
.....
</div>
<div class="one">
.....
</div>
<div class="one">
.....
</div>
我如何选择Nokogiri的第二或第三个div为哪一个?
答案 0 :(得分:7)
您可以使用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选择器查找nth item:
# 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备选方案时请注意:
您可以使用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]')
答案 1 :(得分:5)
page.css('div.one')[1] # For the second
page.css('div.one')[2] # For the third