如何迭代和抓取 Ruby 中的数据?

How to iterate and scrape data in Ruby?

我是编程新手,我的代码需要一些 help/feedback。 我的目标是抓取我的数据,它工作正常,然后在编号列表中向我的用户显示该数据。我只是难以显示这些数据。我没有收到任何错误,我的程序只是完全跳过了我的方法。提前感谢任何 help/feedback!

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

有一些问题可以在此代码中解决,但让我们首先看一下修改:

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

您的 Module/Class 设置看起来不完整。可以这样调用上面的内容:

bp = BestPlaces::Places.new
bp.scrape_places

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