2012-04-22 104 views
6

有了這個HTML代碼:解析HTML與引入nokogiri在Ruby中

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

如何與引入nokogiri選擇第二或第三格,它的類呢?

回答

5
page.css('div.one')[1] # For the second 
page.css('div.one')[2] # For the third 
+2

本來這個答案有CSS'DIV#one' 。這找到了一個* id爲'one'的div,但是HTML有'one'的* classes *。這就是爲什麼我製作了CSS'div.one'。 '#'選擇一個ID,'.'選擇一個類。 – 2012-04-22 23:24:29

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的選擇注意:

  1. 編號從1開始,而不是0
  2. 您可以使用at_cssat_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]') 
+0

非常感謝你提供了大量的例子。我們需要更多這樣的答案! +1 – 2016-03-10 19:18:52