Ruby on rails Nokogiri解析HTML,但只找到第一个匹配项?

Ruby on rails Nokogiri解析HTML,但只找到第一个匹配项?,ruby-on-rails,nokogiri,Ruby On Rails,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"

我有这个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>
输出如下:

96,09 €
63,03€
值不存在。我只发现第一次发生,而不是所有发生。 在此之后,我需要找到
%
值,但这是第二步

你能帮我吗



解决方案是使用
css
而不是
at_css

如果将其更改为

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.

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

干杯

发出打字错误的声音。。但简而言之:不要使用at_css,而只尝试item.css
table.search('table > tr').each do |row|
  puts row.at_css("td.col-price").text.strip
end