LoginSignup
1
1

More than 1 year has passed since last update.

PythonでGoogleAnalyticsからデータを取得する

Posted at

この記事の内容

  • データを取得する基本的な方法
  • filterを使ったデータの絞り込み方
  • よく使うdimensionsとmetrics

参考記事

APIからデータを取得する

前準備

# モジュールをインポート
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
import datetime
import os

# GoogleAnalyticsで設定したキーファイルとビューID等を指定する
SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
KEY_FILE_LOCATION = '生成したJsonファイル.json'
VIEW_ID = 'GAのViewID'

# APIオブジェクトを作成する
credentials = ServiceAccountCredentials.from_json_keyfile_name(KEY_FILE_LOCATION, SCOPES)
analytics = build('analyticsreporting', 'v4', credentials=credentials)

最も簡単な例(国ごとのセッション数を取得する)

response = analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:country'}]
        }]
      }
  ).execute()

データの絞り込み(filter)

例として、日本の絞り込んだセッション数を取得する

response = analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensionFilterClauses': [
              {"filters": [
                  {"dimensionName": "ga:country",
                   "operator": "EXACT",
                   "expressions": 'Japan'}
              ]}
          ],
          pageSize: 50000,
        }]
      }
  ).execute()
  • operatorEXACT(一致)だけでなくGREATER_THAN(指定したものより大きいもの)やREGEXP(正規表現)等がある

※pageSizeはデフォルトで1000なのでそれより大きくなる場合は指定する

よく使うmetrics

metcicsとは:取得したいデータ

metrics 意味
ga:session セッション数
ga:transactionRevenue 収益
ga:transactionsPerSession コンバージョン率
ga:itemQuantity ECでの販売数

※metricsは量的変数、dimensionsは質的変数を担当していると言える

よく使うdimensions

dimensionsとは:データを分類するためのラベル

dimensions 意味
ga:region 地域
ga:country
ga:year
ga:month
ga:day
ga:hour
ga:minute
ga:productBrand ブランド名
ga:productName 商品名
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1