【发布时间】:2020-06-02 15:32:04
【问题描述】:
所以我将网站上的数据抓取到我的scraper.rb 文件中,一切正常。
现在我想用这些数据构建 Table 的类实例,我将其推入一个名为 @tables_new 的数组中。当然我必须 require_relative "table"(我的模型表),但我总是收到这个错误消息 uninitialized constant ApplicationRecord (NameError)。
所以我用谷歌搜索了,当然已经实现了:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
这也无济于事。
另一方面,我能否以某种方式将 @tables_new 数据传递到其他地方并在那里创建 Table 实例?
谁能帮我解决这个问题?
code: scraper.rb
require 'nokogiri'
require 'open-uri'
require 'mechanize'
class PingPongScraper
def initialize
@tables_new = []
@agent = Mechanize.new
end
def fetch_pingpong_tables
num_pages_to_scrape = 1
# num_pages_to_scrape = 290 // all pages to scrap from
count = 0
webcount = 0
while(num_pages_to_scrape > count)
page = @agent.get("website{webcount}").parser # took the original website out here :)
page.css('.list_item .inner').each do |link|
@tables_new << {location: link.content.strip.split("\n")[2].strip, description: link.content.strip.split("\n")[1].strip}
end
webcount += 30
count += 1
end
@tables_new.each do |table|
p table
Table.create!(table)
end
end
end
r = PingPongScraper.new
r.fetch_pingpong_tables
【问题讨论】:
-
如何在脚本中加载 Rails 环境?
-
嗨,我没有在脚本中加载 Rails 环境,这是一个 Rails 应用程序。 github.com/Janis4411/rails-table-tennis
-
你应该加载rails环境。
-
对不起,我对 Rails 和一般编码都很陌生。我不明白你的意思。这个文件 scraper.rb 在我的 rails 应用程序中。它是一个功能齐全的网络应用程序。我只是在使用抓取的数据创建表实例时遇到问题。您能否详细说明您的评论?
标签: ruby-on-rails ruby web-scraping