pekorinko / review_check

0 stars 0 forks source link

Googleの検索画面(「Googleの口コミ」ボタンはある)URLを入力すると「口コミの取得に失敗しましたとエラーが出る #89

Closed pekorinko closed 3 years ago

pekorinko commented 3 years ago

前提

selenium_tool.rbのinitializeメソッドで検索結果URLが入力された場合は自動で「Googleの口コミ」ボタンを押す仕組みを作っている

image

【selenium_tool.rb】
module MyTools
  class SeleniumTool
    attr_reader :url
    def initialize(url)
      @url = url
      options = Selenium::WebDriver::Chrome::Options.new
      options.add_argument('--headless')
      @driver = Selenium::WebDriver.for :chrome, options: options
      @wait = Selenium::WebDriver::Wait.new(timeout: 30)
      @driver.get(@url)

      # モーダルが来ても検索結果が来てもページが表示されたか判別出来るなにかをする
      # begin rescueを使ってタイムアウトしたということは検索画面URLだったと判断する
      begin
        wait.until { @driver.find_element(:class_name, 'lcorif').displayed? }
      rescue StandardError
        replace_url_if_needed
      end
    end

    def replace_url_if_needed
      modal =
        @driver.execute_script(
          'return document.getElementsByClassName("review-dialog-list").length',
        )

      if modal == 0
        @driver.execute_script(
          'document.getElementsByClassName("hqzQac")[0].getElementsByTagName("a")[0].click()',
        )
        sleep 5
        @url = @driver.current_url
        @driver.get(@url)
        @wait.until { @driver.find_element(:class_name, 'lcorif').displayed? }
      end
    end
pekorinko commented 3 years ago

エラー原因の仮説

恐らくresults_controller.rbのcreateメソッド内でbegin~rescueで囲っていることが原因

pekorinko commented 3 years ago

binding.pryの結果

46行目のplace = place_data_scraper.save_placeで何らかのエラーが起こっていることがわかった

pekorinko commented 3 years ago

補足(おさらい):binding.pryの使い方

pekorinko commented 3 years ago

エラーが起こっているplace = place_data_scraper.save_placeの中身を詳しく見てみる

【place_data_scraper save_placeメソッド】
def save_place
      # 口コミが無いGoogleのURLが入力された際に発生するbugの確認をするため、以下のbinding.pryはコメントとして残す
      # binding.pry
      uri = URI.parse(@url)
      @lrd = uri.fragment.split('=')[1].split(',')[0]
      place = Place.find_by(lrd: @lrd)
      @result = @scrape_process.fetch_place

      if place.present?
        place.update(
          place_name: @result[:place_name],
          address: @result[:address],
          star_ave: @result[:star_ave],
        )
        return place
      end
pekorinko commented 3 years ago

検索結果URLだった場合は自動で「Googleの口コミ」ボタンを押してモーダルのURLを取得する処理

【selenium_tool.rbのinitializeメソッド】→place_data_scraper.rbと関連があるため内容を改めて確認

pekorinko commented 3 years ago

解決