※スクレイピングは自己責任でお願いします
参考にさせていただいた記事は以下
こんなかんじの表を
こんなかんじで取り込める
開発環境
ruby 2.6.5
Ruby on Rails 5.2.5
前提
rails
に組み込む想定
基本的なアプリを scaffold
でつくっておく (今回は Post モデル)
方法
① gem 'nokogiri'
で bundle install
② 共通の関数にするために concern
ファイルに以下の module
を作る
concern
module PaypayScrapesConcern
require 'open-uri'
require 'nokogiri'
def set_paypay_shops
url = 'https://paypay.ne.jp/notice/20200604/01/'
doc = Nokogiri::HTML(URI.open(url))
@posts = []
doc.xpath('//div[@class="article__contents post"]').css('tr').each do |node|
@posts << node.css("td[1]").text
end
@posts = @posts.drop(1)
@posts
end
end
Nokogiri::HTML(URI.open(url))
でもとの HTML をひっぱってきて
doc.xpath('//div[@class="article__contents post"]').css('tr').each do |node|
@posts << node.css("td[1]").text
end
で情報を切り出している
③ 今回は post_new_path
のルーティングで表示させるので
new アクションに以下のコードを書く
post_controller.rb
def new
if params[:format] == "paypay"
@posts = set_paypay_shops
end
@post = Post.new
end
クエリパラメーターで条件分岐(これは状況によってはいらない)
④ view
に以下のコード
posts/new.html.erb
<%= link_to "表示する", new_post_path("paypay")%>
<% if @posts.present? %>
<% @posts.each do |post| %>
<%= post%>
<% end %>
<% end %>
get
メソッドなので
new_post_path("paypay")
とすると
irb(#<PostsController:0x00007ffa83a5b498>):001:0> params
=> <ActionController::Parameters {"controller"=>"posts", "action"=>"new", "format"=>"paypay"} permitted: false>
こんな感じでパラメーターをつけられる。format
の使い方間違ってる気がするけど
今回のパターンは new の url で完結するようにした