Można użyć Ruby na pare dół dużej wyników wyznaczonych do poszczególnych przedmiotów:
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
Ponieważ Ruby indeksowanie zaczyna się od zera trzeba zadbać o elementy, które chcesz.
Alternatywnie, można użyć selektorów CSS znaleźć 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)')
Albo można użyć XPath wrócić konkretne mecze:
# 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]")
zarówno z alternatyw CSS i XPath pamiętać, że :
- Numeracja zaczyna się od 1, a nie 0
Zamiast tego można użyć at_css
i at_xpath
, aby odzyskać pierwszy taki pasujący element zamiast zestawu 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)')
Wreszcie, należy pamiętać, że jeśli wybierając jeden element indeksem z XPath można używać krótszy format:
# 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]')
Początkowo ta odpowiedź miała CSS 'div # one' . To znajdzie element div z * id * z 'one', ale HTML ma * klasy * z' one'. Właśnie dlatego stworzyłem plik CSS "div.one". '# 'wybiera ID,' .' wybiera klasę. –