nokogiriとautopagerizeを使ってスクレイピングしてきたデータを、railsのActiveRecordに保存したいのですが、保存の仕方がわからず困っています。
link_checkersテーブルに解析で取得したtitleとurlを格納し、一回一回クロールせずに再利用したいのですが、どのようにしたらいいのでしょうか?
<やったこと>
まずmodelを作成し、http://hoge.xyz/?s=fugaにあるリンクを取得する処理を書き、
↓models/link_checker.rb
class LinkChecker < ApplicationRecord require "multi_json" require "autopagerize" require 'nokogiri' require 'open-uri' def initialize() url = "http://hoge.xyz/?s=fuga" siteinfo = MultiJson.load(File.read("siteinfo.json")) @page = Autopagerize.new(url, siteinfo, :maxpage => 2) end def get_nextlink @links = [] @page.each do |page| doc = Nokogiri::HTML.parse(page.html) @elements= doc.xpath('//*[contains(@id, "post-")]') @elements.each do |a| link = a.xpath('div/header/h2/a').attribute('href') @links << link end end @links.uniq! @links end end
次に、controllerで解析し、取得したtitleとurlを@andにハッシュ形式で渡し、viewでeachを回すことでブラウザ上に表示できました。
↓controllers/link_checker.rb
class LinkCheckersController < ApplicationController def index crawler = Post.new @links = crawler.get_nextlink @and = {} @links.each do |link| charset = nil html = open(link) do |f| charset = f.charset f.read end doc = Nokogiri::HTML.parse(html, nil, charset) title = doc.xpath('//*[contains(@id, "post-")]/article/header/h1').text url = doc.xpath('//*[@id="the-content"]/h2/span/a').attribute('href').text @and.store(title, url) end end end
しかし、これだとDBに格納されていないので、DBに保存したいです。
これを以下のようにしましたがエラーがでます。
ここを変更することでDBに保存することもできるようになると思うのですが、どのようにしたらいいのでしょうか?
class LinkCheckersController < ApplicationController def index end def show end def new @crawler = LinkChecker.new links = @crawler.get_nextlink links.each do |link| charset = nil html = open(link) do |f| charset = f.charset f.read end doc = Nokogiri::HTML.parse(html, nil, charset) @crawler.title = doc.xpath('//*[contains(@id, "post-")]/article/header/h1').text #これと @crawler.url = doc.xpath('//*[@id="the-content"]/h2/span/a').attribute('href').text #これを保存したい @crawler.save end end end
テーブルは以下のようになっています。
create_table "link_checkers", force: :cascade do |t| t.string "title" t.string "url" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/22 07:17