Google Search Console の URL Inspection API を呼び出しページのクロール情報を取得する - C#

Google Search Console の URL Inspection API を呼び出しページのクロール情報を取得するコードを紹介します。

概要

こちらの記事ではGoogle Search Console APIを呼び出し、 Google Serach Consoleの情報を取得するコードを紹介しました。 紹介したSearch Console APIとは別に、URL単位での情報を取得する URL Inspection API が新しく提供されました。
この記事では、URL Inspection API を呼び出してURLごとのクロール情報を取得するコードを紹介します。
メモ
URL Inspection APIは、1分間に600回の呼び出し、1日に2,000回の呼び出し制限があるため、 調査するURL数が多い状況で実運用で利用する場合は、バッチプログラムで構築しURLをローテーションしながら呼び出す必要があります。

事前準備

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

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

キーファイルの配置

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

UI

下図のフォームを作成します。ボタンとテキストボックスと、複数行のテキストボックス(Multilineプロパティをtrueに設定)を配置します。

コード

using Google.Apis.Auth.OAuth2;
using Google.Apis.SearchConsole.v1.Data;
using Google.Apis.SearchConsole.v1;
using Google.Apis.Services;
using System.Text;

namespace SimpleUrlInspectionAPICall
{
  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"
      });

      InspectUrlIndexRequest iuir = new InspectUrlIndexRequest();
      iuir.InspectionUrl = textBox2.Text;
      iuir.SiteUrl = "sc-domain:(取得したいドメイン)";
      iuir.LanguageCode = "ja-JP";

      InspectUrlIndexResponse resp = service.UrlInspection.Index.Inspect(iuir).Execute();

      StringBuilder sb = new StringBuilder();

      sb.Append(string.Format("Verdict: {0}", resp.InspectionResult.IndexStatusResult.Verdict));
      sb.Append("\r\n");
      sb.Append(string.Format("CoverageState: {0}", resp.InspectionResult.IndexStatusResult.CoverageState));
      sb.Append("\r\n");
      sb.Append(string.Format("RobotsTxtState: {0}", resp.InspectionResult.IndexStatusResult.RobotsTxtState));
      sb.Append("\r\n");
      sb.Append(string.Format("IndexingState: {0}", resp.InspectionResult.IndexStatusResult.IndexingState));
      sb.Append("\r\n");

      if (resp.InspectionResult.IndexStatusResult.LastCrawlTime != null) {
        DateTime LastCrawl = (DateTime)resp.InspectionResult.IndexStatusResult.LastCrawlTime;
        sb.Append("LastCrawlTime: " + LastCrawl.ToString("yyyy/MM/dd HH:mm:ss"));
      }
      else {
        sb.Append("LastCrawlTime: none");
      }

      sb.Append(string.Format("PageFetchState: {0}", resp.InspectionResult.IndexStatusResult.PageFetchState));
      sb.Append("\r\n");
      sb.Append(string.Format("GoogleCanonical: {0}", resp.InspectionResult.IndexStatusResult.GoogleCanonical));
      sb.Append("\r\n");
      sb.Append(string.Format("UserCanonical: {0}", resp.InspectionResult.IndexStatusResult.UserCanonical));
      sb.Append("\r\n");
      if (resp.InspectionResult.IndexStatusResult.Sitemap != null) {
        int smapCount = resp.InspectionResult.IndexStatusResult.Sitemap.Count;
        for (int i = 0; i < smapCount; i++) {
          sb.Append(string.Format("Sitemap {0:d}: {1}", i, resp.InspectionResult.IndexStatusResult.Sitemap[i]));
        }
      }
      else {
        sb.Append("Sitemap: none");
      }
      sb.Append("\r\n");

      if (resp.InspectionResult.IndexStatusResult.ReferringUrls != null){
        int refCount = resp.InspectionResult.IndexStatusResult.ReferringUrls.Count;
        sb.Append(string.Format("Reffering Urls: {0:d}", refCount));
        sb.Append("\r\n");
        for (int i = 0; i < refCount; i++) {
          sb.Append(string.Format("Reffering Url {0:d}: {1}", i, resp.InspectionResult.IndexStatusResult.ReferringUrls[i]));
          sb.Append("\r\n");
        }
      }
      else {
        sb.Append("Reffering Urls: none");
      }

      sb.Append(string.Format("CrawledAs: {0:d}", resp.InspectionResult.IndexStatusResult.CrawledAs));
      sb.Append("\r\n");

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

解説

認証やSearchConsoleService オブジェクトの作成はGoogle Serach Console APIを呼び出す場合と同様です。 ロジックの詳細はこちらの記事を参照して下さい。
  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"
  });

URL Inspection API の Inspectメソッドを呼び出す際のパラメーターを準備します。 InspectUrlIndexRequest オブジェクトを作成し、InspectionUrl に取得したいURLを設定します。今回はフォームの上部のテキストボックス(textBox2)に 入力された文字列を利用します。
SiteUrl には取得するURLを集計している Google Serach Consoleアカウントのドメインを設定します。
LanguageCode には言語を指定します。今回は日本語の情報を取得するため、"ja-JP" を設定します。
      InspectUrlIndexRequest iuir = new InspectUrlIndexRequest();
      iuir.InspectionUrl = textBox2.Text;
      iuir.SiteUrl = "sc-domain:(取得したいドメイン)";
      iuir.LanguageCode = "ja-JP";

URL Inspection API の Inspect メソッドを呼び出します。Execute() メソッドを実行します。
APIの結果は、InspectUrlIndexResponse オブジェクトとして取得できます。
      InspectUrlIndexResponse resp = service.UrlInspection.Index.Inspect(iuir).Execute();

以下のコードで InspectUrlIndexResponse オブジェクトの値をテキストボックスに表示します。
     StringBuilder sb = new StringBuilder();

      sb.Append(string.Format("Verdict: {0}", resp.InspectionResult.IndexStatusResult.Verdict));
      sb.Append("\r\n");
      sb.Append(string.Format("CoverageState: {0}", resp.InspectionResult.IndexStatusResult.CoverageState));
      sb.Append("\r\n");
      sb.Append(string.Format("RobotsTxtState: {0}", resp.InspectionResult.IndexStatusResult.RobotsTxtState));
      sb.Append("\r\n");
      sb.Append(string.Format("IndexingState: {0}", resp.InspectionResult.IndexStatusResult.IndexingState));
      sb.Append("\r\n");

      if (resp.InspectionResult.IndexStatusResult.LastCrawlTime != null) {
        DateTime LastCrawl = (DateTime)resp.InspectionResult.IndexStatusResult.LastCrawlTime;
        sb.Append("LastCrawlTime: " + LastCrawl.ToString("yyyy/MM/dd HH:mm:ss"));
      }
      else {
        sb.Append("LastCrawlTime: none");
      }

      sb.Append(string.Format("PageFetchState: {0}", resp.InspectionResult.IndexStatusResult.PageFetchState));
      sb.Append("\r\n");
      sb.Append(string.Format("GoogleCanonical: {0}", resp.InspectionResult.IndexStatusResult.GoogleCanonical));
      sb.Append("\r\n");
      sb.Append(string.Format("UserCanonical: {0}", resp.InspectionResult.IndexStatusResult.UserCanonical));
      sb.Append("\r\n");
      if (resp.InspectionResult.IndexStatusResult.Sitemap != null) {
        int smapCount = resp.InspectionResult.IndexStatusResult.Sitemap.Count;
        for (int i = 0; i < smapCount; i++) {
          sb.Append(string.Format("Sitemap {0:d}: {1}", i, resp.InspectionResult.IndexStatusResult.Sitemap[i]));
        }
      }
      else {
        sb.Append("Sitemap: none");
      }
      sb.Append("\r\n");

      if (resp.InspectionResult.IndexStatusResult.ReferringUrls != null){
        int refCount = resp.InspectionResult.IndexStatusResult.ReferringUrls.Count;
        sb.Append(string.Format("Reffering Urls: {0:d}", refCount));
        sb.Append("\r\n");
        for (int i = 0; i < refCount; i++) {
          sb.Append(string.Format("Reffering Url {0:d}: {1}", i, resp.InspectionResult.IndexStatusResult.ReferringUrls[i]));
          sb.Append("\r\n");
        }
      }
      else {
        sb.Append("Reffering Urls: none");
      }

      sb.Append(string.Format("CrawledAs: {0:d}", resp.InspectionResult.IndexStatusResult.CrawledAs));
      sb.Append("\r\n");

      textBox1.Text += sb.ToString();

実行結果

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


[button1]をクリックします。認証処理等があるため、若干時間がかかります。


URL Inspection API を呼び出し、結果がテキストボックスに表示されます。指定したURLがインデックスに登録されているかの状態や、 最終クロール日時、参照URLなどの情報が取得できます。


作成したばかりのページの情報を取得した結果が下図です。
インデックスに未登録の状態や、ページ取得ができたかの状態や、最終クロール日がない情報が表示できています。

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