
RailsとHerokuでYahooニュースのスクレイピングを定期実行してみた
Ruby on Railsとherokuを使ってYahooニュースを毎朝7:00に定期的にスクレイピングを実行し、そのままWEBサイトのページに表示させるプログラムを作ってみました。
Railsを使ってのスクレイピングを実行環境で実行するまでにバイナリの設定などエラーで困っている方はこれを参考にしていただければと思います。
controller
controllerのcreateアクション内にスクレイピングのコードを書いた例です。
webdriverの設定をしています。
def create
require "selenium-webdriver"
require "webdrivers"
options = Selenium::WebDriver::Chrome::Options.new
options.binary = ENV.fetch('GOOGLE_CHROME_SHIM', nil)
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
driver = Selenium::WebDriver.for :chrome, options: options
driver.get("URL")
# 以下スクレイピングプログラム
driver.quit
end
スクレイピングの結果をデータベースに保存
webページ内の特定の要素を検索しデータ収集。
ここではScrapeDatumという名前のデータベースに保存しています。
# ページ内の複数の要素からデータを取得する場合
contents = driver.find_elements("複数要素")
for i in contents do
begin
title = i.find_element("要素")
rescue => error
Rails.logger.error "Error getting price: #{error.message}"
end
# 作成したデータベースに保存
ScrapeDatum.create(title: title)
end
データベースに保存した後ページ転移して結果を表示
# 取得したうちの10件だけshowアクションに値を渡す
@latest_scrape_data = ScrapeDatum.order(created_at: :desc).limit(10)
# 出力したいcontrollerのviewsに転移します(scrapeの場合)
redirect_to scrape_path(@latest_scrape_data)
views
viewsでWEB上から入力された値を受け取るためのフォームの作成
# cssのbootstrapを使ってます
<div class="container">
<div class="p-1">
<%= form_with url: scrape_index_path, method: :post, local: true do |form|
<%= form.label :keyword, "検索キーワード" %>
<%= form.text_field :keyword, placeholder => "ご希望の商品を入力"
<%= form.submit "スクレイピング開始" %>
<% end %>
</div>
</div>
ここから先は
3,025字
¥ 300

励みになります! よろしくお願いします!