【问题标题】:How to iterate and scrape data in Ruby?如何在 Ruby 中迭代和抓取数据?
【发布时间】:2017-10-28 11:46:16
【问题描述】:

我对编程很陌生,需要一些关于我的代码的帮助/反馈。 我的目标是抓取运行良好的数据,然后在编号列表中向我的用户显示该数据。我只是很难显示这些数据。我没有收到任何错误,我的程序完全跳过了我的方法。提前感谢您的任何帮助/反馈!

class BestPlaces::Places
  attr_accessor :name, :population, :places
    @@places = []

  def self.list_places
    # puts "this is inside list places"
    self.scrape_places
  end

      def self.scrape_places
        doc = Nokogiri::HTML(open("https://nomadlist.com/best-cities-to-live"))
            places = doc.search("div.text h2.itemName").text
            rank = doc.search("div.rank").text

            places.collect{|e| e.text.strip}
              puts "you are now in title"
              @@places << self.scrape_places
              puts "#{rank}. #{places}"
            end
          end
        end

CLI Page:
class BestPlaces::CLI

  def list_places
    puts "Welcome to the best places on Earth!"
    puts @places = BestPlaces::Places.list_places
  end

  def call
    list_places
    menu
    goodbye
  end
end

【问题讨论】:

  • 你如何运行你的代码?
  • 本地,在我的 bin 文件夹中只有一个 CLI 程序
  • 您必须调用您的方法,即BestPlaces::Places.list_places(我认为这是您的入口点)。把它放在文件的底部。看起来你在@@places &lt;&lt; self.scape_places 行有无限循环。
  • 是的,list_places 是我的切入点。谢谢,我会玩循环。我确实想将数据推送到数组中。
  • 另外,1) 检查你的ends,你的BestPlaces::Places 班级似乎有一个闲逛; 2) places.collect 将失败,因为doc.search("div.text h2.itemName").text 中的text 将返回一个String 对象。

标签: arrays ruby iteration scrape


【解决方案1】:

在这段代码中有一些事情可以解决,但让我们先看看重新设计:

require 'nokogiri'
require 'open-uri'

module BestPlaces

  class Places
    attr_accessor :name, :population, :places

    def initialize
      @places = []
    end

    def scrape_places
      doc = Nokogiri::HTML(open("https://nomadlist.com/best-cities-to-live"))
      places = doc.search("div.text h2.itemName")
      ranks = doc.search("div.rank")
      places.each{|e| @places << e.text.strip}
      puts "you are now in title"
      @places.each do |place|
        i = @places.index(place)
        puts "#{ranks[i].text}. #{place}"
      end
   end

 end

 class CLI

   def list_places
     puts "Welcome to the best places on Earth!"
     BestPlaces::Places.scrape_places
   end

   def call
     list_places
     menu
     goodbye
   end

 end

end

您的模块/类设置看起来不完整。可以这样称呼上面的:

bp = BestPlaces::Places.new
bp.scrape_places

@@places 变量是不必要的,我们可以使用@places 来保存需要在 Places 类中访问的值。此外,在搜索结果中使用 .text 方法时,nokogiri 会返回一个字符串对象,这意味着您不能像数组一样遍历它们。我希望这会有所帮助。

【讨论】:

  • 谢谢大家!非常感谢您的反馈!
  • 这会是我的推送方法无法被 ruby​​ 识别的原因吗?我的程序没有将我的“
  • 如果你指的是你在 self.scrape_places 中的推送方法,你试图推送一个不存在的值,例如该方法没有返回语句来实际返回某些东西。您可能还想查看herehere 以获取有关返回语句和“
猜你喜欢
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
  • 2018-07-25
  • 2021-04-17
  • 2023-02-11
  • 1970-01-01
  • 2021-09-29
  • 2014-02-26
相关资源
最近更新 更多