この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Google Analytics の PV を集計し、ダウンロードしたい
Google Analytics は Web サイト向けのアクセス解析サービスです。Web ページに JavaScript コードを設定するだけで簡単にページビュー (PV) を集計できます。最もポピュラーなアクセス解析サービスであり、国内・国外問わずほとんどの Web サイトで導入されています。
集計結果は Web 管理画面から閲覧することができますが、別な用途で使いたい場合はエクスポートが必要です。そこで本記事では Google API の Node.js クライアントライブラリである「google-api-nodejs-client」を使って、プログラムから取得してみました。
検証環境
- macOS Sierra 10.12.3
- Node.js v6.11.0
- google-api-nodejs-client 20.0.1
事前準備
プログラミングに入る前に、Google API にアクセスするための認証情報を取得する必要があります。まずはその作業から始めましょう。
Google API コンソールでプロジェクトを作成する
まずは以下にアクセスし、新規プロジェクトを作成します。
Analytics API を有効化し、クレデンシャルファイルをダウンロードする
次に Google API にアクセスするための認証クライアントを作成します。以下にアクセスし「Analytics API」を選びます。
上部の「有効化する」をクリックします。有効化されたら「認証情報を作成」をクリックします。
「API を呼び出す場所」は「ウェブサーバー」、「アクセスするデータの種類」は「アプリケーションデータ」を選択します。
「サービスアカウント名」は適当に決め、「役割」は「プロジェクト」の中の「閲覧者」を選択します。「サービスアカウント ID」は後で必要になるのでメモしておいてください。「キーのタイプ」は「JSON」を選択します。
自動的に JSON ファイルがダウンロードされます。こちらがクレデンシャルファイルです。key.json
にリネームしておきます。こちらは後で使います。
Google Analytics の閲覧権限を与える
対象の Web サイトの Google Analytics にて権限を付与します。Google Analytics の管理画面の「ビュー」の「ビュー設定」を表示し、「ビュー ID」をメモしておきます。こちらは、後でプログラムで使用します。
次に「ユーザー管理」を表示し、先ほどメモしたサービスアカウント ID (example@utopian-plane-xxxxxx.iam.gserviceaccount.com
のようなもの) を追加します。
以上で権限設定については終わりです。
google-api-nodejs-client の導入
まずは Node.js プロジェクトを作成しましょう。適当なディレクトリを作成し、次の package.json
ファイルを作成します。
package.json
{
"name": "ga",
"version": "1.0.0",
"description": "",
"main": "ga.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "suwa.yuki",
"private": "true",
"dependencies": {
"googleapis": "^20.0.1"
}
}
npm install
(yarn を使う場合は yarn install
) を実行します。
$ npm install
もし package.json
をすでに作成済みなのであれば、以下のコマンドを実行します。
$ npm install googleapis --save
yarn を使う場合は以下のコマンドになります。
$ yarn add googleapis
実装
先ほどダウンロードした JSON ファイルは JWT 形式の認証情報です。こちらをワークディレクトリ直下に置きつつ、以下を実装します。
ga.js
'use strict'
// google-api-nodejs-client を利用
const google = require('googleapis');
// JWT 形式の認証情報をインポート
const key = require('./key.json');
// 使っているのは client_email と private_key (pem) だけ
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
// scope は以下を指定
['https://www.googleapis.com/auth/analytics.readonly'],
null
);
// Google Analytics のクライアントを利用
const analytics = google.analytics('v3');
// 認証
jwtClient.authorize((err, tokens) => {
if (err) {
console.log(err);
return;
}
analytics.data.ga.get({
// ここで JWT クライアントを設定
'auth': jwtClient,
'ids': 'ga:' + '<ビュー ID>',
'start-date': '2017-07-01',
'end-date': '2017-07-07',
'metrics': 'ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits',
'dimensions': 'ga:pagePath',
'sort':'-ga:pageviews'
}, (err, resp) => {
if (err) {
console.log(err);
return;
}
console.log(JSON.stringify(resp));
});
});
実行
以下のコマンドを実行すると output.json
として出力できます。
$ node ga.js | jq . >! output.json
取得したレスポンス
こんな感じのデータが取れます(長いので一部省略)。
{
"kind": "analytics#gaData",
"id": "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxxxxx&dimensions=ga:pagePath&metrics=ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits&sort=-ga:pageviews&start-date=2017-07-01&end-date=2017-07-07",
"query": {
"start-date": "2017-07-01",
"end-date": "2017-07-07",
"ids": "ga:xxxxxxxx",
"dimensions": "ga:pagePath",
"metrics": [
"ga:pageviews",
"ga:uniquePageviews",
"ga:timeOnPage",
"ga:bounces",
"ga:entrances",
"ga:exits"
],
"sort": [
"-ga:pageviews"
],
"start-index": 1,
"max-results": 1000
},
"itemsPerPage": 1000,
"totalResults": xxxx,
"selfLink": "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxxxxx&dimensions=ga:pagePath&metrics=ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits&sort=-ga:pageviews&start-date=2017-07-01&end-date=2017-07-07",
"nextLink": "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:xxxxxxxx&dimensions=ga:pagePath&metrics=ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits&sort=-ga:pageviews&start-date=2017-07-01&end-date=2017-07-07&start-index=1001&max-results=1000",
"profileInfo": {
"profileId": "xxxxxxxx",
"accountId": "xxxxx",
"webPropertyId": "UA-xxxxx-x",
"internalWebPropertyId": "xxxxxxxx",
"profileName": "example.jp",
"tableId": "ga:xxxxxxxx"
},
"containsSampledData": false,
"columnHeaders": [
{
"name": "ga:pagePath",
"columnType": "DIMENSION",
"dataType": "STRING"
},
{
"name": "ga:pageviews",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "ga:uniquePageviews",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "ga:timeOnPage",
"columnType": "METRIC",
"dataType": "TIME"
},
{
"name": "ga:bounces",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "ga:entrances",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "ga:exits",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"totalsForAllResults": {
"ga:pageviews": "xxxxx",
"ga:uniquePageviews": "xxxxx",
"ga:timeOnPage": "x.xxx",
"ga:bounces": "xxxxx",
"ga:entrances": "xxxxx",
"ga:exits": "xxxxx"
},
"rows": [
[
"/path/to/page",
"xxxxx",
"xxxxx",
"xxxxx.x",
"xxxxx",
"xxxxx",
"xxxxx"
],
[
"/path/to/page",
"xxxxx",
"xxxxx",
"xxxxx.x",
"xxxxx",
"xxxxx",
"xxxxx"
],
[
"/path/to/page",
"xxxxx",
"xxxxx",
"xxxxx.x",
"xxxxx",
"xxxxx",
"xxxxx"
],
...
]
}
まとめ
Google Analytics の集計データを簡単にプログラムから取得できました。Web サイトの運用の際にはぜひ参考にしてください!