ローカル環境ではselenuiumが動いても、herokuなどの実行環境ではデータが取得できないと思います。
その際の設定をまとめました。
HerokuでRubyアプリケーションの設定
$ heroku buildpacks:set heroku/ruby
HerokuのGoogle Chromeビルドパックを追加
$ heroku buildpacks:add https://github.com/heroku/heroku-buildpack-google-chrome.git
HerokuのChromedriverビルドパックを追加
$ heroku buildpacks:add https://github.com/heroku/heroku-buildpack-chromedriver.git
環境変数を設定(PATHを通す)
$ heroku config:set GOOGLE_CHROME_BIN=/app/.apt/usr/bin/google-chrome
$ heroku config:set GOOGLE_CHROME_SHIM=/app/.apt/usr/bin/google-chrome
$ heroku config:set WD_CHROME_PATH=/app/.apt/usr/bin/google-chrome
ビルドパックの確認は
$ heroku buildpacks
Seleniumの設定を更新
Webdrivers::Chromedriver.update
# このupdateがないとバイナリーが見つかりにくかったりしたのでポイントです
require "selenium-webdriver"
require "webdrivers"
options = Selenium::WebDriver::Chrome::Options.new
options.binary = ENV['GOOGLE_CHROME_SHIM']
options.add_argument('--headless')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')
driver = Selenium::WebDriver.for :chrome, options: options
バイナリーが無事設定できるか確認するには、
herokuのdyno内でシェルを動かします
$ heroku run bash
chromeのバイナリが存在するか確認
$ ls /app/.apt/usr/bin/google-chrome
エラーがでなかったらOK
herokuでのchromeバージョン確認
$ heroku run google-chrome --version
herokuでのchromedriverのバージョン確認
$ heroku run chromedriver -v
herokuでのchromeバージョンを指定して設定する場合
$ heroku config:set GOOGLE_CHROME_VERSION=あなたのバージョン
設定後、アプリの再デプロイ
$ git commit --allow-empty -m "add Google_Chrome_version"
$ git push heroku main
herokuのビルドパックをクリアするには
$ heroku buildpacks:clear
Herokuのchromedriverとwebdriverのバージョンが一致せずchromdriverのバージョンを指定するには
'config/initializers/webdrivers.rb'を作成して初期設定をします。
$ touch config/initializers/webdrivers.rb
作成したファイルに
Webdrivers::Chromedriver.required_version = 'あなたの指定バージョン'
CROMEDRIVER_VERSIONのバイナリーを設定したい時
$ heroku config:set CHROMEDRIVER_VERSION="設定したい値"
CHROM
これでheroku上でseleniumを動かすことができます。