前回投稿したyahoo広告自動抽出の記事に続いて、Googleも記録として残しておこうと思います。
Yahoo 広告の数値を自動取得してみた(GAS)
前回はGASで実装したので、今回はお得意のPythonで実装してみたいと思います。
Googleは割とブログに残している方も多く、Yahooよりも設定が分かりやすく説明してくれているので、正直リファレンスだけでできてしまうなーとは思いつつ、自分の復習のためにも残しておこうかと。。。。
Google広告管理画面側での設定
まずは、Google広告側の設定をしていきます。
以下説明する内容は、Google Ads APIのリファレンスを抜粋してご説明いたします。
1.Google広告管理画面にログイン
2.ツールと設定からAPIセンターをクリック
3.必要情報を入力し、API申請(トークンが発行されるまでには、3日~1週間ぐらいかかります)
4.クライアントライブラリを自分のPCに落としてくる
https://developers.google.com/google-ads/api/docs/first-call/get-client-lib
上記URLにアクセスし、希望の言語のクライアントライブラリをローカルにおとします。
今回はpythonで実装予定なのでpythonタブから赤線部分をクリック

Read meファイルを参照し、pipで希望のローカルの場所にインストール
pip install google-ads
5.Google API consoleでプロジェクトを作成する
Google Ads APIを使用するために、API consoleで設定
google広告管理画面と同じGアカウントにて以下URLにアクセス
https://console.developers.google.com/project
プロジェクトを作成をクリックし、任意の名前を入力し、プロジェクト作成

6.Google Ads APIを有効化
上記URLのAPIライブラリにアクセスし、「google ads api」と入力
一番上にでてくる「Google Ads API」をクリックし、有効化


7.クライアントIDとクライアントシークレットを作成する
APIにアクセスするためのキーを作成
上記URLの認証情報にアクセスし、「認証情報を作成」「OauthクライアントID」→をクリック

最初にOauthを登録する場合、同意画面がでてくるので、
ユーザーの種類を外部OR内部を選択し、アプリ名を任意の名前を入力
その後、同意へ進む
画面が戻るので、OauthクライアントIDの作成に戻る
アプリケーションの種類は「デスクトップアプリ」を選択し、任意の名前を入力し、作成をクリック

その後、クライアントIDとシークレットが発行されるので、コピーしておく

8.リフレッシュトークンを取得する
Oauthの作成が完了したら、クライアントIDやシークレットの情報が入っているjsonファイルをダウンロード

{
"installed": {
"client_id": "hoge.apps.googleusercontent.com",
"project_id": "precise-rite-999999",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://www.googleapis.com/oauth2/v3/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "fuga",
"redirect_uris": [
"urn:ietf:wg:oauth:2.0:oob",
"http://localhost"
]
}
}
# フォーマット
{auth_uri}
?client_id={client_id}
&redirect_uri={redirect_uris(httpの方)}
&scope=https://www.googleapis.com/auth/adwords
&access_type=offline
&response_type=code
# URL
https://accounts.google.com/o/oauth2/auth?client_id=hoge.apps.googleusercontent.com&redirect_uri=http://localhost&scope=https://www.googleapis.com/auth/adwords&access_type=offline&response_type=code
上記のようにURLを作成し、ブラウザでアクセス

リダイレクト後のURLをコピーする
※画面はエラーが表示されますが、正常な動作なので問題ないです

http://localhost/?code=4/test&scope=https://www.googleapis.com/auth/adwords
その後、ターミナルORコマンドプロンプトにてCURLをたたいてリフレッシュトークンを取得してください
# フォーマット
# curl -d client_id={client_id} -d client_secret={client_secret} -d redirect_uri={redirect_uris(httpの方)} -d grant_type=authorization_code -d code={認証コード(4.で取得したURLのcodeパラメータ)} https://accounts.google.com/o/oauth2/token
$ curl -d client_id=test.apps.googleusercontent.com -d client_secret=fuga -d redirect_uri=http://localhost -d grant_type=authorization_code -d code=4/test https://accounts.google.com/o/oauth2/token
{
"access_token": "nyaaa",
"expires_in": 3600,
"refresh_token": "1/test",
"scope": "https://www.googleapis.com/auth/adwords",
"token_type": "Bearer"
}
数値を取得してみる
APIの申請完了通知後、実際にGoogle 広告の数値を取得してみます
取得する際に、最後の設定として、クライアントライブラリのyamlファイルに開発者トークン、クライアントID、シークレット、リフレッシュトークンを記載していきます。
pythonのクライアントライブラリで取得したgoogle-ads.yamlファイルの中に記載します。
# OAuth2 configuration
###############################################################################
# The below configuration parameters are used to authenticate using the #
# recommended OAuth2 flow. For more information on authenticating with OAuth2 #
# see: https://developers.google.com/google-ads/api/docs/oauth/overview #
###############################################################################
developer_token: INSERT_DEVELOPER_TOKEN_HERE
client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
# Login customer ID configuration
###############################################################################
# Required for manager accounts only: Specify the login customer ID used to #
# authenticate API calls. This will be the customer ID of the authenticated #
# manager account. It should be set without dashes, for example: 1234567890 #
# instead of 123-456-7890. You can also specify this later in code if your #
# application uses multiple manager account + OAuth pairs. #
###############################################################################
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
# Service Account configuration
###############################################################################
# To authenticate with a service account add the appropriate values to the #
# below configuration parameters and remove the four OAuth credentials above. #
# The "path_to_private_key_file" value should be a path to your local private #
# key json file, and "delegated_account" should be the email address that is #
# being used to impersonate the credentials making requests. for more #
# information on service accounts, see: #
# https://developers.google.com/google-ads/api/docs/oauth/service-accounts #
###############################################################################
# path_to_private_key_file: INSERT_PATH_TO_JSON_KEY_FILE_HERE
# delegated_account: INSERT_DOMAIN_WIDE_DELEGATION_ACCOUNT
# Logging configuration
###############################################################################
# Below you may specify the logging configuration. This will be provided as #
# an input to logging.config.dictConfig. Use the "level" block under the root #
# logger configuration to adjust the logging level. Note in the "format" #
# field that log messages are truncated to 5000 characters by default. You #
# can change this to any length by removing the ".5000" portion or changing #
# it to a different number. #
# #############################################################################
# logging:
# version: 1
# disable_existing_loggers: False
# formatters:
# default_fmt:
# format: '[%(asctime)s - %(levelname)s] %(message).5000s'
# datefmt: '%Y-%m-%d %H:%M:%S'
# handlers:
# default_handler:
# class: logging.StreamHandler
# formatter: default_fmt
# loggers:
# "":
# handlers: [default_handler]
# level: INFO
developer_token = 取得したGoogle広告管理画面に記載の開発者トークンを記載
client_id,client_secret,refresh_token = 上記で取得したものを記載
login_customer_id = 取得したいGoogle広告のアカウント毎にカスタマーIDを記載
以上ですべての設定が完了しました。実際に数値を取得してみましょう。
クライアントライブラリで取得したファイルの中にサンプルファイルがあるので、その中のキャンペーン名取得ファイルを実行してみます。
ファイルの保存先は、Google-ads-python/examples/get_campaigns.pyになります。
上記のファイルをターミナルORコマンドプロンプトで実行してみるとキャンペーン名が取得できると思います。
おまけ
pythonファイルのyamlファイルの読み込みは実際にパスを書いてもOKです。
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to get all campaigns.
To add campaigns, run add_campaigns.py.
"""
import argparse
import sys
from google.ads.google_ads.client import GoogleAdsClient
from google.ads.google_ads.errors import GoogleAdsException
def main(client, customer_id):
ga_service = client.get_service('GoogleAdsService', version='v3')
query = ('SELECT campaign.id, campaign.name FROM campaign '
'ORDER BY campaign.id')
# Issues a search request using streaming.
response = ga_service.search_stream(customer_id, query=query)
try:
for batch in response:
for row in batch.results:
print(f'Campaign with ID {row.campaign.id.value} and name '
f'"{row.campaign.name.value}" was found.')
except GoogleAdsException as ex:
print(f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:')
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f'\t\tOn field: {field_path_element.field_name}')
sys.exit(1)
if __name__ == '__main__':
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
google_ads_client = GoogleAdsClient.load_from_storage(r"C:\Users\test_name\google-ads-python\google-ads.yaml")
parser = argparse.ArgumentParser(
description='Lists all campaigns for specified customer.')
# The following argument(s) should be provided to run the example.
parser.add_argument('-c', '--customer_id', type=str,
required=True, help='The Google Ads customer ID.')
args = parser.parse_args()
main(google_ads_client, args.customer_id)
google_ads_client = GoogleAdsClient.load_from_storage(r”C:\Users\test_name\google-ads-python\google-ads.yaml”)
上記の()の中身にyamlファイルをみにいくようにパスを設定してあげます。
おそらく特に変更しなくても、みにいってくれるようにexampleファイルはなっていると思いますが、エラーでみにいけてないようであれば直接パスを指定してあげるといいかと思います。
また、上のコードの説明をすこしだけ。
取得する内容を変更したいときは、
query = (‘SELECT campaign.id, campaign.name FROM campaign ‘
‘ORDER BY campaign.id’)
上記の部分を変更することにより、取得内容を変更することが可能です。
単純なSQL文で取得することができます。
取得する内容については、以下のリファレンスを見ながら実装してみてください。
https://developers.google.com/google-ads/api/fields/v4/overview
また以下のURLを参照すれば、この指標とりたいんだけど、どんな名前なんだろうといったときに便利です。SQL文を自動生成してくれるので、生成されたものをそのままコピペするだけで使えます。
https://developers.google.com/google-ads/api/docs/query/interactive-gaql-builder
とはいえ、非エンジニアには難しいかも。。。

おそらく業務効率化のために広告の数値を自動抽出したいというマーケターの方が多く、手作業で行っている会社もまだまだ多いでしょう。
社内にエンジニアもいなく、いざやってみようと思っても、難しい用語や設定でやっぱ無理となってしまう人も少なくないかと思います。
もし、実際にやってみて挫折した方や自由にこういう設定もしてみたいという方はご連絡いただければ、ぜひご助力させていただきます。
こちらのサイトのお問い合わせでも構いませんし、twitter宛でもご対応いたします!(プロフィール記載)
私もまだまだ駆け出しエンジニアですが、手作業の負をなるべく無くしていくように会社の業務効率化を推進しております。
今まではデータ周り整備をメインにやってきましたが、最近は開発周りをやらせていただけており、やっぱ開発するのはわくわくするなーと思ってきた次第です。
データ系より楽しくなってきちゃいました(笑)
では、また!