GAのデータインポート機能について、ご存じでしょうか。
普段、広告代理店で働くマーケターの方は広告の費用とGAの数値を一緒にみたいと思ったことが一度はあると思います。
GAでは、Google広告の連携はできますが、Yahoo広告やSNS広告の数値は連携できないので、他のBIツールで表現するしか表現方法ないと思っていませんか?
実は、GAにデータをインポートして、GA上でみることができるようになります。要するに、広告の費用対効果ぐらいであれば、GAでみれてしまうのです。
目次
GAのインポート機能とは。。。
GAのインポート機能とは、正確には、オフラインのビジネス システムで生成されたデータと、アナリティクスで収集したオンライン データを結合できる機能です。
たとえば、個別の CRM データ、e コマースデータ、アナリティクス データを 1 つのビューにまとめて表示して、ビジネスの全容を把握することができます。
私が実際に行っていることとしては、広告の費用対効果って広告だけじゃなくて、GA上の数値と比較して全体的にどれくらいの費用対効果なのか、広告単体でみたら、KPI達成しているけど、本当にそのKPIでいいのかな。と思ったときに必要だなと思って広告費用をインポートしてみました。
本当は会社にDWH、BIツールを導入して、それで可視化し、分析するのが一般的だと思いますが、会社にエンジニアがいなかったら、そんなことはできないと思うので、、、、、。
Google広告とYahoo広告の数値を自動でインポート
まず完全に自動化するためにGoogle広告とYahoo広告の数値を抽出して、CSVに落とす作業を自動化する必要があります。
そちらの方法は以下の記事にて記載しております。
Google広告の数値を自動抽出してみた【Python】
Yahoo 広告の数値を自動取得してみた(GAS)
設計としては、Google広告、Yahoo広告のそれぞれの数値を自動で抽出し、CSVに保存。そのCSVをそれぞれGAにインポートするという流れです。
実際の作業の流れ
GAインポートを自動化するためには、まずGAAPIを設定する必要があります。
こちらはGoogle広告APIの設定とほぼ同じです。
GAAPIの設定
以下のURLが公式のリファレンスになります。
https://developers.google.com/analytics/devguides/reporting/core/v3?hl=ja
こちらを抜粋してご説明いたします。
今回はpythonで実装していますので、pythonのやり方になりますが、他の言語でもやり方はほぼ同じです。もし他の言語で実装したいという方はご連絡ください。
1.アナリティクスAPIを有効にする
まずは、GAのAPIを使いますよという設定をします。
以下URLにアクセスし、Google API Consoleでプロジェクトを作成します。
※Google広告の自動抽出が済んでいる方は、すでに作成済みのプロジェクトを選択いただいて大丈夫です。

その後、左のタブから「認証情報」をクリックし、「認証情報を作成」→「サービスアカウント」をクリックしてください

任意の名前とメールアドレスを入力し、作成をクリック

すると、APIconsoleのサービスアカウントが作成されますので、メールアドレスをコピーしておきます。
また、サービスアカウントを作成した際にキーが発行されると思いますので、client_secrets.json
というファイル名で保存します。こちらはGAAPIにアクセスできるキーですので、大切に保管しておいてください。
もしキーが紛失してしまった場合はAPIConsoleのサービスアカウントからまた再度発行はできるのでご安心を。

その後、GAにログインし、先ほどコピーしたメールアドレスをユーザー情報に追加してください。
ユーザーの追加方法については、
管理→アカウントユーザーの管理→+マーク→ユーザーを追加→メールアドレスコピペの流れです。
権限は「編集権限」で追加してください。
こちら「編集権限」でないとインポート機能は使えないのでご注意ください。
2.Googleのクライアントライブラリをインストール
※Google広告APIですでにインストールされている方は不要です。
以下のコマンドをターミナルORコマンドプロンプトにて入力し、pythonのパッケージを取得します。
sudo pip install --upgrade google-api-python-client
3.サンプルを実行する
設定は2で完了です。
最後にちゃんと動くかどうか確認してみましょう。
以下のスクリプトをコピーして、先ほどダウンロードしたclient_secrets.json
ファイルを同じディレクトリに保存してください。
以下のように、コードの内容を修正してください。
key_file_location = ‘<REPLACE_WITH_JSON_FILE>’
↓
key_file_location = ‘client_secret.json’
そして、実行してみると、、、、
Google アナリティクス ビュー(旧プロファイル)の名前と、
過去 7 日間のセッション数が出力されます。
以上で接続は完了しました!!
"""A simple example of how to access the Google Analytics API."""
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
def get_service(api_name, api_version, scopes, key_file_location):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scopes: A list auth scopes to authorize for the application.
key_file_location: The path to a valid service account JSON key file.
Returns:
A service that is connected to the specified API.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
# Build the service object.
service = build(api_name, api_version, credentials=credentials)
return service
def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.
# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()
if accounts.get('items'):
# Get the first Google Analytics account.
account = accounts.get('items')[0].get('id')
# Get a list of all the properties for the first account.
properties = service.management().webproperties().list(
accountId=account).execute()
if properties.get('items'):
# Get the first property id.
property = properties.get('items')[0].get('id')
# Get a list of all views (profiles) for the first property.
profiles = service.management().profiles().list(
accountId=account,
webPropertyId=property).execute()
if profiles.get('items'):
# return the first view (profile) id.
return profiles.get('items')[0].get('id')
return None
def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='7daysAgo',
end_date='today',
metrics='ga:sessions').execute()
def print_results(results):
# Print data nicely for the user.
if results:
print 'View (Profile):', results.get('profileInfo').get('profileName')
print 'Total Sessions:', results.get('rows')[0][0]
else:
print 'No results found'
def main():
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = '<REPLACE_WITH_JSON_FILE>'
# Authenticate and construct service.
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
profile_id = get_first_profile_id(service)
print_results(get_results(service, profile_id))
if __name__ == '__main__':
main()
GAインポート機能を実装してみる
では、本題のインポートのやり方です!
やり方というか、あとはスクリプト書くだけなんですけどね(笑)
おそらくほとんどの方が「はやくスクリプトみたい」と思っていると思うので、先に貼りますね。
# -*- coding: utf-8 -*-
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.http import MediaFileUpload
import os
#----------------------------------------------------------------------------------------------------------------------------------------------------------------
#----------csvファイル指定-----------------------
gss_file = 'AdData_gss.csv'
gdn_file = 'AdData_gdn.csv'
yss_file = 'AdData_yss.csv'
ydn_file = 'AdData_ydn.csv'
#----------GAアカウントID------------------------
GA_accountId = 'GAのアカウントIDを記載してください'
#----------プロパティ------------
GA_webPropertyId = 'UAから始まるプロパティIDを記載してください'
google_customDataSourceId = 'GAで作成したインポートのデータソースを記載してください'
yahoo_customDataSourceId = 'GAで作成したインポートのデータソースを記載してください'
#----------------------------------------------------------------------------------------------------------------------------------------------------------------
def get_service(api_name, api_version, scopes, key_file_location):
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
#serviceオブジェクトを作成
service = build(api_name, api_version, credentials=credentials)
return service
def csvdata_import(service, select_csv, webPropertyId, customDataSourceId):
media = MediaFileUpload(select_csv,
mimetype='application/octet-stream',
resumable=False)
daily_upload = service.management().uploads().uploadData(
accountId=GA_accountId,
webPropertyId=webPropertyId,
customDataSourceId=customDataSourceId,
media_body=media).execute()
print (daily_upload)
def main(get_medium_csv, select_csv, webPropertyId, customDataSourceId):
#GAに接続するためのスコープを設定、jsonファイル指定
scope = 'https://www.googleapis.com/auth/analytics.edit'
key_file_location = 'client_secret.json'
#認証設定
service = get_service(
api_name='analytics',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
#csvファイルがあるものだけ、GAに自動インポート
if os.path.exists(get_medium_csv) == True:
csvdata_import(service, select_csv, webPropertyId, customDataSourceId)
if __name__ == '__main__':
main (gss_csv, gss_file, GA_webPropertyId, google_customDataSourceId)
main (yss_csv, yss_file, GA_webPropertyId, yahoo_customDataSourceId)
軽く説明すると、、、
まず、上記のスクリプトはGoogle広告とYahoo広告の数値を取得し、GAのインポート用に整形されたCSVを読み込んでインポートするスクリプトになります。
中身の例としては、以下のような感じです。
ga:date | ga:source | ga:medium | ga:campaign | ga:adContent | ga:adCost | ga:impressions | ga:adClicks |
20200802 | cpc | test | 1 | 1000 | 432430 | 423 | |
20200802 | cpc | test | 2 | 1000 | 432430 | 423 | |
20200802 | cpc | test | 3 | 1000 | 432430 | 423 |
上記の内容のCSVをGoogleとYahooでそれぞれ用意し、GA上にそれぞれデータインポート用のデータソースを作成してインポートするという形です。
GAインポート用のデータソースというのは、GA上にインポート用に作成する箱みたいなもので、詳細は以下の方の記事が参考になるかと思います。
https://ayudante.jp/column/2019-06-27/08-00/
上記のファイルを定期実行設定することで、毎日インポートするようにしております。
まとめ

やはり、ちょっと難しいですね。少しエンジニアの知識がある方であれば、簡単だとは思いますが、まったくわからないからスタートするのは結構勇気がいることだと思います。
ただ、IT業界にいる以上PCスキルが必要なくなることはないので、
これを気に実際に手を動かしてみるのもいいかもしれません。
では、また。
コメントを残す