2014-04-03 25 views
0

我有這樣的HTML:Nokogiri解析HTML但僅查找第一個出現?

<div class="pl-item-content clear" style="width: 176px; height: 385.875px;"> 
    <div class="pricing-info-container"> 
    <table cellspacing="0" class="product-prices"> 
     <colgroup> 
     <col class="col-name"><col class="col-price"> 
     </colgroup> 
     <tbody> 
     <tr> 
     <th class="col-name" scope="row">Prezzo a catalogo</th> 
     <td class="col-price">96,09 €</td> 
     </tr> 
     <tr> 
     <th class="col-name" scope="row">Prezzo</th> 
     <td class="col-price">63,00 €</td> 
     </tr> 
     <tr> 
     <th class="col-name" scope="row">Risparmio</th> 
     <td class="col-price col-saving">34,4%</td> 
     </tr> 
     <tr> 
     <th class="col-name" scope="row">Disponibilità</th> 
     <td class="col-price"><div class="stock-value"><span>16</span></div></td> 
     </tr> 
     </tbody> 
    </table> 
    </div> 
</div> 

我有很多pl-item-content塊,所以我需要進行迭代。

我需要找到價格和%值:96,09,63,00,34,4

我正在使用Nokogiri解析HTML文檔並提取一些信息。我曾嘗試與此:

doc.css('div.pl-item-content').each do |item| 
    puts item.at_css(".pricing-info-container .product-prices td.col-price").text.strip 
end 

輸出是這樣的:

96,09 € 

63,03 €值不存在。我只找到第一次發生,而不是所有的發生。 在此之後,我需要找到%值,但這是第二步。

你能幫我嗎?


的解決方案是使用css代替at_css

+1

woops一個錯字,但..在短:而不是使用at_css只嘗試item.css – AndreDurao

回答

1

它的工作原理,如果你將其更改爲

doc.css('div.pl-item-content').each do |item| 
    puts item.css(".pricing-info-container .product-prices td.col-price").text.strip 
end 

在引入nokogiri文檔,它說:

- (Object) at_css(*rules) 
Search this node for the first occurrence of CSS rules. Equivalent to css(rules).first See Node#css for more information. 
+0

?你的代碼和我的一樣 – user1066183

0

引入nokogiri的at_css也只返回查詢相匹配的第一個元素。嘗試類似的東西:

doc.search('div.pl-item-content').each do |table| 
    table.search('table > tr').each do |row| 
    puts row.at_css("td.col-price").text.strip 
    end 
end 

也許仍然需要一些調整...去爲它。如果你都不會在意哪個表與實際投放數據,只是試試這個:

table.search('table > tr').each do |row| 
    puts row.at_css("td.col-price").text.strip 
end 

乾杯