###前提・実現したいこと
現在ゲームのキャラクターの能力値をnokogiriでスクレイピングしてきて、そのデータをrailsのActiveRecordに保存し、いつでもそのデータを見ることができるアプリを制作しています。
対象のページから欲しいデータは無事スクレイピングできたのですが、取得したデータをどのようにActiveRecordに保存すれば良いか分からず、詰まっています...
- スクレイピングで取ってきたデータをActiveRecordに入れる方法を教えていただけると嬉しいです。
よろしくお願いします。
###該当のソースコード
・スクレイピング用のruby
ruby
1require 'nokogiri' 2require 'open-uri' 3require 'open_uri_redirections' 4 5doc = Nokogiri::HTML(open('対象ページのURL')) 6 7(1..302).each do |line| 8 doc.xpath("//*[@id='tablepress-15']/tbody/tr[#{line}]").each do |node| 9 name = node.css('td[2]').inner_text.to_s #キャラクター名 10 hit_point = node.css('td[4]').inner_text.to_i #以下はキャラクターの能力値です 11 attack = node.css('td[5]').inner_text.to_i 12 block = node.css('td[6]').inner_text.to_i 13 contact = node.css('td[7]').inner_text.to_i 14 deffence = node.css('td[8]').inner_text.to_i 15 speed = node.css('td[9]').inner_text.to_i 16 sum = node.css('td[10]').inner_text.to_i 17 end 18end
・migrationファイル
class CreatePokemons < ActiveRecord::Migration def change create_table :pokemons do |t| t.string :name #キャラクター名 t.integer :hit_point #以下能力値 t.integer :attack t.integer :block t.integer :contact t.integer :deffence t.integer :speed t.integer :sum t.timestamps null: false end end end
情報不足でしたらいつでもおっしゃってください。
###補足情報
- ruby
- Ruby on Rails
拙い説明で申し訳ありませんがご回答よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。