Google Search Console APIを呼び出し、検索パフォーマンス情報を取得する - C#

Google Search Console APIを呼び出して検索パフォーマンス情報を取得するコードを紹介します。

概要

Google Search ConsoleのWeb画面では検索パフォーマンス情報を1,000件までしか取得できませんが、APIから情報を取得すると1,000件以上の情報を取得できます。
この記事では、C#を利用して、Google Search Console APIを呼び出して、検索パフォーマンスの情報を取得するコードを紹介します。

事前準備

Google Search Console APIを利用可能な状態にします。また、サービスアカウントを作成し、Google Search Consoleに追加します。 手順の詳細はこちらの記事を参照してください。

プログラム例

.NET 6でWindows Formアプリケーションを作成します。

パッケージのインストール

Google.Apis.SearchConsole.v1 のパッケージをインストールします。

NuGetパッケージコンソールからインストールする場合は、以下のコマンドを実行します。
最新のバージョン番号は NuGetのパッケージページ(https://www.nuget.org/packages/Google.Apis.SearchConsole.v1)にて確認してください。
Install-Package Google.Apis.SearchConsole.v1 -Version 1.57.0.2792

パッケージのインストールの詳しい手順は以下の記事を参照して下さい。

キーファイルの配置

ダウンロードしたキーファイルをプロジェクトに配置します。配置したJSONファイルの[出力ディレクトリにコピー]を変更し、ファイルをコピーする設定に変えます。

UI

下図のフォームを作成します。ボタンと複数行のテキストボックスを配置します。

コード

下記のコードを記述します。配置したボタンのクリックイベントを実装ししています。
using System.Text;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.SearchConsole.v1;
using Google.Apis.SearchConsole.v1.Data;

namespace SimpleAPICall
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      string credentialsPath = "api-project-604973771331-561b5886ff93.json";
      string searchConsoleUrl = "sc-domain:(Google Search Consoleで取得するドメイン名)";

      FileStream stream = new FileStream(credentialsPath, FileMode.Open);
      GoogleCredential credentials = GoogleCredential.FromStream(stream);

      if (credentials.IsCreateScopedRequired)
      {
        credentials = credentials.CreateScoped(new string[] { SearchConsoleService.Scope.Webmasters });
      }

      SearchConsoleService service = new SearchConsoleService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credentials,
        ApplicationName = "Demo App"
      });

      DateTime startDate = DateTime.Now.AddDays(-30);
      DateTime endDate = DateTime.Now;

      List<string> dimensionList = new List<string>();
      dimensionList.Add("query");

      SearchAnalyticsQueryRequest request = new SearchAnalyticsQueryRequest();

      request.StartDate = startDate.ToString("yyyy-MM-dd");
      request.EndDate = endDate.ToString("yyyy-MM-dd");
      request.RowLimit = 10;
      request.StartRow = 0;
      request.Type = "web";
      request.Dimensions = dimensionList;

      SearchAnalyticsQueryResponse response = service.Searchanalytics.Query(request, searchConsoleUrl).Execute();

      StringBuilder sb = new StringBuilder();

      sb.AppendLine("Query\tClicks\tImpressions\tCTR\tAvgPosition");

      if (response.Rows != null)
      {
        foreach (var row in response.Rows)
        {
          sb.Append(row.Keys[0]);
          sb.Append("\t");
          sb.Append(row.Clicks);
          sb.Append("\t");
          sb.Append(row.Impressions);
          sb.Append("\t");
          sb.Append(row.Ctr);
          sb.Append("\t");
          sb.Append(row.Position);
          sb.AppendLine();
        }
      }

      textBox1.Text += sb.ToString();
    }
  }
}

解説

json形式のキーファイルの名称と、Google Search Consoleで取得するドメイン名を設定します。 searchConsoleUrlには、WebでGoogle Search Consoleにアクセスした際のresuource_idパラメーターの値と同じ文字列を設定します。
      string credentialsPath = "api-project-604973771331-561b5886ff93.json";
      string searchConsoleUrl = "sc-domain:(Google Search Consoleで取得するドメイン名)";



JSONファイルを開くためのFileStream を作成し、GoogleCredential オブジェクトを作成します。
      FileStream stream = new FileStream(credentialsPath, FileMode.Open);
      GoogleCredential credentials = GoogleCredential.FromStream(stream);

      if (credentials.IsCreateScopedRequired)
      {
        credentials = credentials.CreateScoped(new string[] { SearchConsoleService.Scope.Webmasters });
      }

Google Search ConsoleにアクセスするためのSearchConsoleServiceオブジェクトを作成します。 作成したオブジェクトのHttpClientInitializer に先に準備したGoogleCredential オブジェクトを設定します。 ApplicationName にはこのアプリケーションの名称を設定します。
      SearchConsoleService service = new SearchConsoleService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credentials,
        ApplicationName = "Demo App"
      });

クエリのリクエストを作成します。リクエストは SearchAnalyticsQueryRequest オブジェクトを作成します。
StartDate EndtDate プロパティにデータを取得する期間を設定します。RowLimitには取得するデータの件数、RowLimit には取得するデータの開始位置を指定します。 RowLimitは25,000まで指定できます。
Type には "web" を指定します。Dimensions には今回は検索パフォーマンスのデータを取得しますので "query" を指定します。
詳しくは(https://developers.google.com/webmaster-tools/v1/searchanalytics/query)を参照してください。
      DateTime startDate = DateTime.Now.AddDays(-30);
      DateTime endDate = DateTime.Now;

      List<string> dimensionList = new List<string>();
      dimensionList.Add("query");

      SearchAnalyticsQueryRequest request = new SearchAnalyticsQueryRequest();

      request.StartDate = startDate.ToString("yyyy-MM-dd");
      request.EndDate = endDate.ToString("yyyy-MM-dd");
      request.RowLimit = 10;
      request.StartRow = 0;
      request.Type = "web";
      request.Dimensions = dimensionList;
作成したSearchAnalyticsQueryRequest オブジェクトをSearchConsoleServiceオブジェクトのQueryメソッドで実行します。 結果は、SearchConsoleService オブジェクトで取得します。
      SearchConsoleServiceresponse = service.Searchanalytics.Query(request, searchConsoleUrl).Execute();

結果をテキストボックスに表示します。
      StringBuilder sb = new StringBuilder();

      sb.AppendLine("Query\tClicks\tImpressions\tCTR\tAvgPosition");

      if (response.Rows != null)
      {
        foreach (var row in response.Rows)
        {
          sb.Append(row.Keys[0]);
          sb.Append("\t");
          sb.Append(row.Clicks);
          sb.Append("\t");
          sb.Append(row.Impressions);
          sb.Append("\t");
          sb.Append(row.Ctr);
          sb.Append("\t");
          sb.Append(row.Position);
          sb.AppendLine();
        }
      }

      textBox1.Text += sb.ToString();

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックします。Google Search Console APIを呼び出し検索パフォーマンスの情報を取得します。取得した結果がテキストボックスに表示されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2022-05-12
iPentec all rights reserverd.