プログラミング素人のはてなブログ

プログラミングも電気回路も専門外の技術屋の末端が勉強したことや作品をアウトプットするブログ。コードに間違いなど見つけられたら、気軽にコメントください。 C#、Python3、ラズパイなど。

pythonでGoogle APIを使ってAnalyticsの情報を取得する

f:id:s51517765:20190328221111p:plain
はてなブログアクセス解析は情報が少なく、過去の履歴も1週間分しかありません。
これでは物足りないので、なにか方法はないか?と考えたところGoogle analyticsが使えそうで、しかもAPIがあります。
そこで、Google analyticsはてなブログのアクセス数(Daily)を取得することをやってみました。

Google analyticsがすでに埋め込まれていて、データが取得できていることが前提です。

まずはGoogle APIを有効にします。
APIの有効化は↓の記事の通りにやればできました。
blog.cosnomi.com

pythonスクリプトを作ります。基本的にはGoogle APIの公式ページのものを使いました。
developers.google.com

 key_file_location = '<REPLACE_WITH_JSON_FILE>'

ここの部分は自分のJSONファイル名とパスを指定します。
ダウンロードしたJSONをmainのスクリプトと同じ場所に置くなら、osモジュールを使用して、

key_file_location = os.getcwd() +"/"+ 'xxxx.json'  # JSON

のように書くこともできます。

google APIのモジュールをインポートします。

$pip install --upgrade google-auth-oauthlib
$pip install --upgrade google-api-python-client

これで、基本的には動くはず…と思いきや、

from apiclient.discovery import build
ImportError: No module named apiclient.discovery

Errorを吐かれました。

importを変更します。

from apiclient.discovery import build
↓
from googleapiclient.discovery import build

stackoverflow.com

公式のドキュメント通りで動かないとはどういうことなんでしょう???
もしかしたらpythonのversionとかもあるのかもしれませんが。(当方python3.5です…)

Installing collected packages: google-auth-oauthlib, pyasn1
  Found existing installation: pyasn1 0.1.9
Cannot uninstall 'pyasn1'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

またErrorを吐かれました。

こんな時は、Errorを無視する?みたいなオプションを付けてpip installします。

$pip install --upgrade google-auth-oauthlib --ignore-installed

qiita.com

またまたError。

“TypeError: cannot instantiate ctype 'EVP_MD_CTX' of unknown size” while trying to build google prediction api

ぐぐると以下のようなStackoverflowがありました。

pip install --upgrade pyOpenSSL

stackoverflow.com


これで、動かしてみると有効にし忘れたところがあるようで、

googleapiclient.errors.HttpError: 
<HttpError 403 when requesting https://www.googleapis.com/analytics/v3/management/accounts?alt=json 
returned "Project 834633458561 is not found and cannot be used for API calls. If it is recently created, 
enable Google Analytics API by visiting
 https://console.developers.google.com/apis/api/analytics.googleapis.com/overview?project=834633458561 then retry. 
If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">

これを修正して、Google analyticsAPIの呼び出しに成功しました。

> View (Profile): すべてのウェブサイトのデータ
> Total Sessions: 280

算出期間の指定は、start_dateとend_dateで指定します。

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='1daysAgo',
        end_date='1daysAgo', # 最新データまでふくめるなら 'today'
        metrics='ga:sessions').execute()

昨日の分だけなら、start_date='1daysAgo'end_date='1daysAgo'とします。
start_dateはstart_date='700daysAgo'のように、かなり前も指定できるようです。
このブログでは、設置がこのぐらい前なので、それ以上はどうなのかわかりませんが。

アクセス数が欲しいだけなら…

スプレッドシートのほうが早いことにあとで気づいた。
service.plan-b.co.jp