LoginSignup
0
0

More than 1 year has passed since last update.

Search Console API と Ruby on Rails

Last updated at Posted at 2023-02-04

はじめに

昔つくったプログラムを思い出に残しておきます。
最新の情報ではありません。

Search Consoleからオーガニック流入キーワードを確認できるが、DBに取り込むバッチプログラムを作成し分析できるデータを保存する。Search ConsoleではAPIが用意されているためそれを毎日実行し、必要な情報を取得する。

Search Console API

API 有効化

  1. https://console.cloud.google.com/getting-started?hl=ja&pli=1 ログインする
  2. プロジェクト内で左のバーの中にある「IAMと管理」の「サービスアカウント」という項目を選択
  3. 「サービスアカウントを作成」を選択し、必要事項を記入します。
  4. サービスアカウントの権限を設定します。Google Search Consoleを転送元として用いるために必要な権限は特にありません
  5. 「ユーザーにこのサービスアカウントへのアクセスを許可」のステップでは特に入力することはありません。作成し終わった後、作成したサービスアカウントに対して「鍵を作成」の操作を行います。キーのタイプはJSONを選択してください。
  6. 左上の「ナビゲーションメニュー」>「APIとサービス」>「ライブラリ」を選択し、検索欄に「Google Search Console」と入力し、「Google Search Console API」を選択します。
    image-20211220-052225.png
  7. 有効にする
  8. Goole Search Console 左のバーから「設定」に進み、「所有権の確認」をクリックします。
  9. 「あなたは確認済みの所有者です」の右下にある「詳細」をクリックします。
  10. 「サイト所有者を追加」のボタンをクリックして作成したサービスアカウントのメールアドレスを入力します。

Ruby on Rails

Gemfileのインストール

gem 'google-apis-searchconsole_v1', '~> 0.1'

Model

SearchConsole コンストラクタでAPIにアクセスするAPIクライアント作成
queryメソッドに検索条件を渡せば、検索してくれる

require 'google/apis/searchconsole_v1'

# SearchConsoleのAPIのmodelクラス
class SearchConsole
  SITE_URL = 'https://xxxx.xxxx.xxx'.freeze
  MAX_ROWS = 25_000

  def initialize
    authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open(Rails.root.join('config', 'connect-to-search-console-api-bec3dfd010b7.json')),
      scope: %w[https://www.googleapis.com/auth/webmasters]
    )
    @client = Google::Apis::SearchconsoleV1::SearchConsoleService.new
    @client.authorization = authorizer
  end

  # 日付は必須です
  # rowLimit Valid range is 1–25,000; Default is 1,000
  def query(start_date, end_date, dimensions = nil, row_limit = nil)
    request = Google::Apis::SearchconsoleV1::SearchAnalyticsQueryRequest.new
    request.start_date = start_date.strftime('%Y-%m-%d')
    request.end_date = end_date.strftime('%Y-%m-%d')
    request.dimensions = dimensions if dimensions.instance_of?(Array)
    request.row_limit = row_limit if row_limit.present?

    @client.query_searchanalytic(SITE_URL, request)
  end
end

これをRakeタスクとかから呼んで、DBに登録する。

    # 流入キーワードとLPのURLを取得
    dimensions = %w[query page]
    search_console = SearchConsole.new
    response = search_console.query(start_date, end_date, dimensions, SearchConsole::MAX_ROWS)
    raise 'nothing found for keywords' if response.nil?

    response.rows.each do |row|
      keyword = row.keys[0]
      lp = row.keys[1]
      position = row.position
      impression = row.impressions
      click = row.clicks
      ctr = row.ctr
    end

reference

かなり使いづらいです。

誰かの何かにお役に立つことを願いつつ。以上となります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0