以前グーグルアナリティクスのアクセスデータをPythonからGoogleAPI経由で取得したのですがアナリティクスがGA4に移行したことでGA4用にプログラムを改修する必要が出てきたので、その際に調べたコードをメモしておきます。同じような方の参考になれば幸いです。
基本的には公式ドキュメントのサンプルコードをそのまま実装することで動作します
前準備
モジュールのインストール
必要なライブラリをpip(macはpip3)でインストールします
$ pip install google-api-python-client $ pip install google-analytics-data
サービスアカウントの確認と権限の付与
公式ドキュメントの「Enable the Google Analytics Data API v1」という青いボタンをクリックして新規プロジェクトを作成します。

次にサービスアカウントのjsonファイルを取得します。

これでダウンロードしたjsonファイルのパスを以下のプログラムの変数 KEY_FILE_LOCATIONに指定します。加えてそのjsonのemailの部分に記載されているサービスアカウント(xxxx.iam.gserviceaccount.com)を変数 SERVICE_ACCOUNT_EMAILに記載します。
VIEW_IDはanalyticsのデータを取得したプロジェクト名の下に記載されている数字を指定します
<イメージ例>
KEY_FILE_LOCATION = "xxxx.json" SERVICE_ACCOUNT_EMAIL = 'xxxx.iam.gserviceaccount.com' VIEW_ID = 'xxxx'
最後にPCブラウザからグーグルアナリティクスにアクセスし該当プロジェクトの「プロパティのアクセス管理」に先ほど確認したサービスアカウントを閲覧者以上のロールとしてアクセス権限を付与します。
また「Analytics reporting API」を以下のURLから有効化します。「https://console.cloud.google.com/apis/api/analyticsreporting.googleapis.com/metrics」

これで前準備は完了です
日ごとのアクセス数を取得する
過去7日間の記事ごとのビュー数を取得するサンプルコード
import argparse
import os
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
KEY_FILE_LOCATION = "xxxx.json"
SERVICE_ACCOUNT_EMAIL = 'xxxx.iam.gserviceaccount.com'
VIEW_ID = 'xxxx'
def initialize_analyticsreporting():
"""Initializes an analyticsreporting service object.
Returns: analytics an authorized analyticsreporting servicobject.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
analytics = build('analyticsreporting', 'v4', credentials=credentials)
return analytics
def get_report(analytics):
# Use the Analytics Service Object to query the Analytics Reporting API V4.
return analytics.reports().batchGet(
body={
'reportRequests': [
{
'viewId': VIEW_ID,
'pageSize': 10,
'dateRanges': [
{'startDate': '7daysAgo', 'endDate': 'today'}
],
'metrics': [
{'expression': 'ga:pageviews'},
],
'dimensions': [
{'name': 'ga:pagePath'}, {'name': 'ga:pageTitle'}
],
'orderBys': [
{'fieldName': 'ga:pageviews', 'sortOrder': 'DESCENDING'},
]
}]
}
).execute()
def print_response(response):
"""Parses and prints the Analytics Reporting API V4 response."""
for report in response.get('reports', []):
rows = report.get('data', {}).get('rows', [])
for row in rows:
print(row)
analytics = initialize_analyticsreporting()
response = get_report(analytics)
print_response(response)
これを以下のコードでデータフレームに変換します
data = [] for i in response['reports'][0]['data']['rows']: data.append([i['dimensions'][1], i['metrics'][0]['values'][0]]) import pandas as pd df = pd.DataFrame(data,columns=['title','views']) print(df.head())
パラメーターについて
RunReportRequestのパラメータのうち、使用頻度の高いものを挙げておきます。
| パラメータ | 意味 |
|---|---|
property |
プロパティ ID。properties/{property ID}の形で指定します |
dimensions |
ディメンション(リスト) (詳しいディメンション・指標名はAPI Dimensions & Metrics) |
metrics |
指標(リスト) |
dateRanges |
データ取得期間 |
dimensionFilter |
ディメンションのフィルタを指定します |
その他のオプションについてはこちらから確認できます。
参照:https://zenn.dev/shiroqujira/articles/00ea833a7b11a4

コメント