2012-04-22 9 views
6

Z tego kodu HTML:analizowaniem HTML z Nokogiri w Ruby

<div class="one"> 
    ..... 
</div> 
<div class="one"> 
    ..... 
</div> 
<div class="one"> 
    ..... 
</div> 
<div class="one"> 
    ..... 
</div> 

jaki sposób można wybrać z Nokogiri drugą lub trzecią div, którego klasą jest jeden?

Odpowiedz

5
page.css('div.one')[1] # For the second 
page.css('div.one')[2] # For the third 
+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ę. –

7

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 :

  1. Numeracja zaczyna się od 1, a nie 0
  2. 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]') 
+0

Dziękuję bardzo za mnóstwa przykładów. Potrzebujemy więcej odpowiedzi w ten sposób! +1 –