はてなブログのアクセス解析は情報が少なく、過去の履歴も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
のように書くこともできます。
$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
公式のドキュメント通りで動かないとはどういうことなんでしょう???
もしかしたら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
またまたError。
“TypeError: cannot instantiate ctype 'EVP_MD_CTX' of unknown size” while trying to build google prediction api
ぐぐると以下のようなStackoverflowがありました。
pip install --upgrade pyOpenSSL
これで、動かしてみると有効にし忘れたところがあるようで、
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 analyticsのAPIの呼び出しに成功しました。
> 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