Google Developersのチュートリアルが上手くいかない
おそらく、Google アナリティクス APIをPythonから使おうと思った方はPython クイックスタートを見たのではないでしょうか。ただ、この通り行っていくとステップ3で
Traceback (most recent call last):
File "test.py", line 6, in <module>
from oauth2client.client import SignedJwtAssertionCredentials
ImportError: cannot import name SignedJwtAssertionCredentials
となり上手く動きませんでした。(2016/3/20現在)
結論としては
SignedJwtAssertionCredentials
ではなくServiceAccountCredentials
を使うことで解決しました。
今回は、この変更を適用してpageview数のランキングを出力するsampleを作成しました。
使い方
pythonはPython 2.7.6を使っています。
Python クイックスタートのステップ2まで行い、
- サービスアカウントアドレス(*@*.iam.gserviceaccount.comみたいなやつ)
- P12 キー
を取得してください。
Githubのリポジトリをダウンロードしてください。
先ほど作成したP12キーのファイルをダウンロードしたフォルダ内に配置してください。
jsonファイルの準備をします
cp config.json.sample config.json
config.jsonの中を以下のように編集します。
{
"email": "<your google developer email adress> ex) sample@sample.iam.gserviceaccount.com ",
"key": "<*.p12 path> ex) ./sample-5a5a55a5a5a5.p12",
"start_date": "ランキングの期間の開始日 ex) 2016-02-07",
"end_date": "ランキングの期間の終了日 ex) 2016-03-07",
"home": "解析するページのURL ex) http://qiita.com"
}
以下の二つをpipで入れます
sudo pip install --upgrade google-api-python-client
pip install pyopenssl
実行します
python googel_analystic_api_ranking.py
解説
ランキングの内容を決めているのは以下の部分です。
def get_rankings_results(service, profile_id, config):
return service.data().ga().get(
ids='ga:' + profile_id,
start_date=config['start_date'],
end_date=config['end_date'],
sort='-ga:pageviews',
max_results='10',
dimensions='ga:pageTitle,ga:pagePath',
metrics='ga:pageviews').execute()
sort='-ga:pageviews',
はga:pageviews
によるソートを行い先頭の-
で降順で取得しています。
アナリティクス APIは結果を行列の形で取得します。
この時max_results
でAPIが取得する結果の行数の上限を指定します。
また、dimensions
とmetrics
で取得する内容を決めています。
今回はdimensions
ではページタイトルとページパス、metrics
ではページビュー数を指定しています。
イメージとしてはdimensions
ごとにmetrics
を見るようになっています。
また結果の出力は以下の部分で行っています。
def print_rankings_results(results, home):
# Print data nicely for the user.
if results:
print(u'-----------ランキングTop10-----------')
for col in results.get('rows'):
print(u'{0}\t{1}{2}\t{3}'.format(col[0], home, col[1], col[2]))
else:
print ('No results found')
引数のresults
には先ほどのget_rankings_results
で取得したAPIからの応答が入ります。
また、'results.get('rows')'で結果の各行にアクセスできます。
結果は、dimensions
、metrics
の順番で並んでいるので'results.get('rows')[0][1]'などとすれば、一番目の結果のpagePathを取得できます。