MENU

herokuのfree dynoで新しいタブを開いていくとSelenium::WebDriver::Error::NoSuchWindowError: no such windowが出る

herokuのfree dynoで新しいタブを開いていくとSelenium::WebDriver::Error::NoSuchWindowError: no such windowが出る

 ローカルでは問題なく動いていたコードが、herokuのfree dynoで動かすとエラーが出る。  原因は、herokuのfree dyno上ではなぜか2つ以上タブを開こうとすると、全てのタブを閉じてしまうためだった。

エラーが出たコード

  def click
    current_window = @driver.window_handles.first
    bnrbox_elements_count = @driver.find_elements(:class, 'hoge').count
    bnrbox_elements_count.times do |time|
      @driver.find_elements(:class, 'hoge')[time].find_element(class: 'fuga').click
      sleep 10
      @driver.switch_to.window(current_window)
      sleep 10
    end

エラーログ

heroku上のログ

"current_window: CDwindow-D6C4668AEEEB83702A7F9CF58632EC69"
"@driver.window_handles: [\"CDwindow-D6C4668AEEEB83702A7F9CF58632EC69\", \"CDwindow-182AC1185FA8F7556F41B8FD3D1DF6AC\"]"
"current_window: CDwindow-D6C4668AEEEB83702A7F9CF58632EC69"
"@driver.window_handles: [\"CDwindow-D6C4668AEEEB83702A7F9CF58632EC69\", \"CDwindow-182AC1185FA8F7556F41B8FD3D1DF6AC\"]"
"current_window: CDwindow-D6C4668AEEEB83702A7F9CF58632EC69"
"@driver.window_handles: []"
rake aborted!
Selenium::WebDriver::Error::NoSuchWindowError: no such window
  (Session info: headless chrome=90.0.4430.85)

 3ループ目で新しいタブが開かれず、4ループ目でタブが全て消える。

ローカル(mac)上のログ

"current_window: CDwindow-7208FC7998BE0EFB7AC4B873C2254403"
"@driver.window_handles: [\"CDwindow-7208FC7998BE0EFB7AC4B873C2254403\", \"CDwindow-B172E6F2271A4F1456E0798FFD81F29E\"]"
"current_window: CDwindow-7208FC7998BE0EFB7AC4B873C2254403"
"@driver.window_handles: [\"CDwindow-7208FC7998BE0EFB7AC4B873C2254403\", \"CDwindow-B172E6F2271A4F1456E0798FFD81F29E\", \"CDwindow-038C4341D58D86ED3BB97AB80F5D14CD\"]"

 想定どおりの動作をしている。

対応

リモート環境ではsleep時間を長めにするようにした。これで動くようになった。

  def click
    current_window = @driver.window_handles.first
    bnrbox_elements_count = @driver.find_elements(:class, 'hoge').count
    bnrbox_elements_count.times do |time|
      @driver.find_elements(:class, 'hoge')[time].find_element(class: 'fuga').click
      sleep 30
      @driver.switch_to.window(current_window)
      sleep 30
    end

 残念ながら根本的な対応ではない。。