【问题标题】:How do i get text for each <li> tag under the same div class using Nokogiri如何使用 Nokogiri 为同一 div 类下的每个 <li> 标签获取文本
【发布时间】:2019-08-04 03:56:17
【问题描述】:

我正在使用 Nokogiri (HTML/CSS) 抓取食谱的成分。每种成分都在成分 div 下的 li 中。现在我的代码正在收集所有的成分,而不是在一个字符串中分离。如何将每个 li 文本放入数组中?

网站有这个

<div class="easyrecipe">
 <div class="ingredients">
  <ul>
   <li class="ingredient" itemprop="recipeIngredient"> 1 tbsp flax</l>
   <li class="ingredient" itemprop="recipeIngredient"> 3 tbsp water</l>
   <li class="ingredient" itemprop="recipeIngredient"> ½ cup spelt</l>
  </ul>

我尝试了这个尝试解析它并将成分放入一个数组中

ingredients = page.css("div.easyrecipe").each do |section|
      section.css("li.ingredient").text

我收到了 “1 汤匙亚麻碎 3 汤匙温水½ 杯斯佩尔特”

【问题讨论】:

    标签: ruby html-lists nokogiri screen-scraping


    【解决方案1】:

    首先,您的成分列表在 div.ingredients 内,而在 div.easyrecipe 内。

    其次,您只是打印出每个部分的所有列表文本。而不是添加每个部分的文本。您想添加每种成分的文本。

    我会改为:

    ingredients = page.css("div.easyrecipe").each do |section|
      section.css("li.ingredient").each do |ingredient|
        ingredient.text
    

    导致:

    p ingredients
    = ["1 tbsp ground flax","3 tbsp warm water","½ cup spelt"]
    

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 2017-01-20
      相关资源
      最近更新 更多