Google Analytics Data Export API を使う - ページごとのPV数の取得 - C#

Google Analytics Data Export APIを用いてGoogle AnalyticsのPV数(ページビュー数)を取得します。
サービス終了に関する注意
Google Universal Analytics はサービスを終了したため、現在はこの記事で紹介しているコードは動作しません。 新しい Google Analytics 4 (GA4) プロパティを利用する必要があります。 GA4プロパティからのデータ取得はこちらの記事を参照してください。
注意
Google Analytics Data Export APIの仕様が変わったためかプロファイルの取得はできなくなっていますのでご注意ください。詳しくはこちらの記事を参照してください。
Analyticsの管理画面からプロファイルIDを調べてコード中に記載してください。

準備

Google Data API SDKをインストールします。インストール方法はこちらの記事を参照してください。
また、プロジェクト作成後、Google Data API のライブラリの参照を追加します。Google Data API Client Library の参照方法はこちらの記事を参照してください。

UI

以下のUIを作成します。

コード

以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Analytics;
using Google.GData.Extensions;


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

    private void button1_Click(object sender, EventArgs e)
    {
      string userName = textBox_User.Text;
      string passWord = textBox_Password.Text;
      string profileId = textBox_ProfileID.Text;

      //Google Data Export API 2.4の場合
      string apikey = "AIxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
      string dataFeedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + apikey;

      AnalyticsService service = new AnalyticsService("AnalyticsSampleApp(iPentec)");
      if (!string.IsNullOrEmpty(userName)) {
        service.setUserCredentials(userName, passWord);
      }

      DataQuery query = new DataQuery(dataFeedUrl);
      query.Ids = profileId;
      query.Metrics = "ga:pageviews";
      query.Dimensions = "ga:pagePath";
      query.Sort = "-ga:pageviews";
      query.GAStartDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");
      query.GAEndDate = dateTimePicker_End.Value.ToString("yyyy-MM-dd");

      DataFeed dataFeed = service.Query(query);
      foreach (DataEntry entry in dataFeed.Entries) {
        ListViewItem item = new ListViewItem(entry.Title.Text);
        item.SubItems.Add(entry.Metrics[0].Value);
        listView_PageView.Items.Add(item);
      }
    }
  }
}

解説

  AnalyticsService service = new AnalyticsService("AnalyticsSampleApp(iPentec)");
  if (!string.IsNullOrEmpty(userName)) {
    service.setUserCredentials(userName, passWord);
  }
AnalyticsServiceのインスタンスを作成します。その後setUserCredentials()メソッドを呼び出し認証情報を設定します。

  DataQuery query = new DataQuery(dataFeedUrl);
  query.Ids = profileId;
  query.Metrics = "ga:pageviews";
  query.Dimensions = "ga:pagePath";
  query.Sort = "-ga:pageviews";
  query.GAStartDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");
  query.GAEndDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");
DataQueryクラスのインスタンスを作成し、取得するAnalyticsデータの条件を設定します。
  • Ids → データを取得するAnalyticsのプロファイルID
  • Metrics → 取得する情報
  • Dimensions → 取得する情報の項目(次元)
  • Sort → データのソート順
  • GAStartDate → データの取得する範囲(開始日)
  • GAStartDate → データの取得する範囲(終了日)
となります。今回は、Idsはプロファイル一覧ListViewで選択された要素のAnalyticsプロファイルのIDを用います。GAStartDate,GAEndDateはDateTimePickerの値を用います。

上記以外にもデータの取得最大個数を設定するプロパティなどがあります。詳しくはGoogle Analyttics Data Export APIのリファレンスやGoogle Data API SDKのリファレンスやソースコードを参照してください。ソースコード補完機能で表示されるプロパティ一覧も参考になります。

  DataFeed dataFeed = service.Query(query);
  foreach (DataEntry entry in dataFeed.Entries) {
    ListViewItem item = new ListViewItem(entry.Title.Text);
    item.SubItems.Add(entry.Metrics[0].Value);
    listView_PageView.Items.Add(item);
  }
AnalyticsServiceのインスタンスのQuery()メソッドを呼び出し、PV数を取得します。foreachループを用いて取得したPVをListViewに追加します。

実行結果

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


Username,Password欄にGoogle AnalyticsのログインIDとパスワードを入力します。Profile IDに取得するGoogle AnalyticsのプロファイルIDを入力します。Google AnalyticsのプロファイルIDの取得方法はこちらを参照してください。
テキストボックスに値を入力し、DateTimePickerの値を設定した後、[PV取得]ボタンを押します。


Google AnalyticsからPVの値が取得しされistViewに表示されます。



以前の記事

UI

下図のUIを準備します。こちらの記事で準備したUIの下部にButtonを1つListViewを1つDateTimePickerを2つ追加します。ListViewのViewプロパティはDetailsに設定し、Columnsに2つ要素を追加します。(2列にします。)

コード

ButtonのClickイベントにコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Analytics;
using Google.GData.Extensions;

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

    private void button_GetProfile_Click(object sender, EventArgs e)
    {
      string userName = textBox_User.Text;
      string passWord = textBox_Pass.Text;

      AccountQuery query = new AccountQuery();
      AnalyticsService service = new AnalyticsService("AnalyticsSampleApp(iPentec)");
      if (!string.IsNullOrEmpty(userName)) {
        service.setUserCredentials(userName, passWord);
      }

      AccountFeed accountFeed = service.Query(query);
      foreach (AccountEntry entry in accountFeed.Entries) {
        ListViewItem item = new ListViewItem(entry.Title.Text);
        //item.SubItems.Add(entry.Title.Text);
        item.SubItems.Add(entry.ProfileId.Value);
        listView_Profile.Items.Add(item);
      }
    }

    private void button_GetPV_Click(object sender, EventArgs e)
    {
      string userName = textBox_User.Text;
      string passWord = textBox_Pass.Text;
      string profileId = listView_Profile.SelectedItems[0].SubItems[1].Text;
      
      Google Data Export API 2.3の場合
      const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";

      //Google Data Export API 2.4の場合
       //string apikey = "AIxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
      //string feedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + apikey;

      AnalyticsService service = new AnalyticsService("AnalyticsSampleApp(iPentec)");
      if (!string.IsNullOrEmpty(userName)) {
        service.setUserCredentials(userName, passWord);
      }

      DataQuery query = new DataQuery(dataFeedUrl);
      //query.Ids = profileId; //以前のコード
       query.Ids = "ga:12345678"; // ← Google Analyticsの管理画面で調べたプロファイルIDをここに記載する

      query.Metrics = "ga:pageviews";
      query.Dimensions = "ga:pagePath";
      query.Sort = "-ga:pageviews";
      query.GAStartDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");
      query.GAEndDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");

      DataFeed dataFeed = service.Query(query);
      foreach (DataEntry entry in dataFeed.Entries) {
        ListViewItem item = new ListViewItem(entry.Title.Text);
        item.SubItems.Add(entry.Metrics[0].Value);
        listView_PageView.Items.Add(item);
      }
    }
  }
}

解説

プロファイル取得部分はこちらの記事を参照してください。

PV取得部分
  AnalyticsService service = new AnalyticsService("AnalyticsSampleApp(iPentec)");
  if (!string.IsNullOrEmpty(userName)) {
    service.setUserCredentials(userName, passWord);
  }
AnalyticsServiceのインスタンスを作成します。その後setUserCredentials()メソッドを呼び出し認証情報を設定します。

  DataQuery query = new DataQuery(dataFeedUrl);
  query.Ids = profileId;
  query.Metrics = "ga:pageviews";
  query.Dimensions = "ga:pagePath";
  query.Sort = "-ga:pageviews";
  query.GAStartDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");
  query.GAEndDate = dateTimePicker_Start.Value.ToString("yyyy-MM-dd");
DataQueryクラスのインスタンスを作成し、取得するAnalyticsデータの条件を設定します。
  • Ids → データを取得するAnalyticsのプロファイルID
  • Metrics → 取得する情報
  • Dimensions → 取得する情報の項目(次元)
  • Sort → データのソート順
  • GAStartDate → データの取得する範囲(開始日)
  • GAStartDate → データの取得する範囲(終了日)
となります。今回は、Idsはプロファイル一覧ListViewで選択された要素のAnalyticsプロファイルのIDを用います。GAStartDate,GAEndDateはDateTimePickerの値を用います。

上記以外にもデータの取得最大個数を設定するプロパティなどがあります。詳しくはGoogle Analyttics Data Export APIのリファレンスやGoogle Data API SDKのリファレンスやソースコードを参照してください。ソースコード補完機能で表示されるプロパティ一覧も参考になります。

  DataFeed dataFeed = service.Query(query);
  foreach (DataEntry entry in dataFeed.Entries) {
    ListViewItem item = new ListViewItem(entry.Title.Text);
    item.SubItems.Add(entry.Metrics[0].Value);
    listView_PageView.Items.Add(item);
  }
AnalyticsServiceのインスタンスのQuery()メソッドを呼び出し、PV数を取得します。foreachループを用いて取得したPVをListViewに追加します。

実行結果

アプリケーションを実行すると下図の画面が表示されます。


UserNameにGoogleアカウントのIDを、PasswordにGoogleアカウントのパスワードを入力し、[プロファイル取得]ボタンを押します。ListViewにAnalyticsプロファイルの一覧が表示されます。


プロファイル一覧が表示されているListviewからPVを取得したいプロファイルをクリックして選択します。また、DateTimePickerの開始日と終了日を設定します。設定後PV取得ボタンを押すと、選択したAnalyticsプロファイルのPVを取得し下部のListViewに結果を表示します。


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