Heroku Dyno 上のヘッドレス Google Chrome を使用した Selenium が常にタイムアウトになる
概要
これは似ていますが、重複ではありません: Rails アプリを使用して Heroku で Selenium Webdriver を正しく実行する方法
その質問にある答えをすべて試しましたが、うまくいきません。私の出力は常に次のとおりです。
timed out after 60 seconds (no such element: Unable to locate element: {"method":"css selector","selector":"div.x9f619.x1n2onr6.x1ja2u2z"} (Selenium::WebDriver::Error::TimeoutError)
(Session info: headless chrome=119.0.6045.199); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception)
from /app/lib/scraper/scraper.rb:33:in `load!'
from bin/scrape.rb:21:in `block in <main>'
from bin/scrape.rb:16:in `each'
from bin/scrape.rb:16:in `<main>'
Webドライバーを構築する方法は次のとおりです。
@selenium_options = setup_selenium_opts
if chrome_bin = ENV["GOOGLE_CHROME_REAL"]
Selenium::WebDriver::Chrome.path = chrome_bin
end
if chrome_driver = ENV["CHROME_DRIVER_REAL"]
Selenium::WebDriver::Chrome::Service.driver_path = chrome_driver
end
@driver = Selenium::WebDriver.for(:chrome, options: @selenium_options)
def setup_selenium_opts
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox') # Bypass OS security model
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920x1480')
return options
end
ENV 変数が正しく設定されていることは、heroku run irb を実行し、ENV ハッシュを検査することで確認できます。
私には何が欠けているのでしょうか?
解決策
ヘッドレス Chrome を実行する場合の Python (https://stackoverflow.com/a/73840130/7058266) と同様に、非ヘッドレス Chrome を使用しているときと同じように動作させたい場合は、Chrome の新しいヘッドレス モードを使用する必要があります。オプションとして必要な Ruby 行は次のとおりです。
options.add_argument('--headless=new')
非ヘッドレス モードで動作する場合は、新しいヘッドレス モードでも動作するはずです。