masalibの日記

システム開発、運用と猫の写真ブログです

Google Search ConsoleのAPIでCSV出力した

概要

前回でサンプルで出力できたので
今度はCSV出力するように修正しました
masalib.hatenablog.com


本来ならCSV保存とかやるべきなのですが
めんどくさいので標準の出力で対応しています
CSV出力さえできれば、エクセルやmysqlSQLserver
簡単に取り込む事ができます
サイトのポリシーにもよりますが
特定のワードでランキング計測することを想定しています
pythonなのでたぶんmacwindowscentosなどでも動きます

前提

環境はpython3.4です
2.7にしていないです

プログラム仕様

googleAPIを利用して
 Google Search Consoleのデータを取得してCSV出力する
・表示回数が0の場合はCTRが-になります

実行例
python search-analytics-query-syupro.py http://XXXXXX.com 2015-05-10 2015-05-10 >> resultword.csv
# もし特定の期間の合計値を出したい場合は期間のfrom to を修正してください
python search-analytics-query-syupro.py http://XXXXXX.com 2015-05-11 2015-05-17 >> resultword.csv
# もし特定の期間の個別に実行したい場合はコマンドを複数実行してください
python search-analytics-query-syupro.py http://XXXXXX.com 2015-05-11 2015-05-11 >> resultword.csv
python search-analytics-query-syupro.py http://XXXXXX.com 2015-05-12 2015-05-12 >> resultword.csv
出力フォーマット
yyyy-mm-dd(処理日(to)),['ワード'],クリック数,impressions(表示回数),CTR,position(表示順位)
出力例
2015-05-10,0.0,3.0,0.0,39.0
2015-05-11,0.0,7.0,0.0,51.57142857142857
2015-05-12,0.0,12.0,0.0,44.0
2015-05-13,0.0,8.0,0.0,49.375
2015-05-14,0.0,9.0,0.0,37.55555555555556
2015-05-15,0.0,15.0,0.0,52.333333333333336
2015-05-16,0.0,21.0,0.0,44.476190476190474

ソース

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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
#
#      http://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.

import argparse
import sys
from googleapiclient import sample_tools

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('property_uri', type=str,
                       help=('Site or app URI to query data for (inclufing '
                             'trailing slash).'))
argparser.add_argument('start_date', type=str,
                       help=('Start date of the requested date range in '
                             'YYYY-MM-DD format.'))
argparser.add_argument('end_date', type=str,
                       help=('End date of the requested date range in '
                             'YYYY-MM-DD format.'))


def main(argv):
  service, flags = sample_tools.init(
      argv, 'webmasters', 'v3', __doc__, __file__, parents=[argparser],
      scope='https://www.googleapis.com/auth/webmasters.readonly')

# masalib 追記
# dimensionFilterGroupsを追加することでフィルタリングができる
# 下記の例は対象ワードを修正する事で絞込をしている
# 出力する行数はrowLimitで制限できる(デフォルト1000)
  request = {
      'startDate': flags.start_date,
      'endDate': flags.end_date,
      'dimensions': ['query'],
      'dimensionFilterGroups': [{
         'filters': [{
              'dimension': 'query',
              'expression': '対象ワード'
          }],
      }]

  }
  response = execute_request(service, flags.property_uri, request)

# masalib 追記
# パラメータの3番目(対象日(To))を渡す事でレコードの最初に日付を出力
  print_table(response, 'Available dates',argv[3])

def execute_request(service, property_uri, request):
  return service.searchanalytics().query(
      siteUrl=property_uri, body=request).execute()


def print_table(response, title,procdate):

  if 'rows' not in response:
    print ('Empty response')
    return

  rows = response['rows']

  for row in rows:
    keys = ''
    if 'keys' in row:
      keys = u','.join(row['keys']).encode('utf-8')
    print ( str(procdate) + ',' + str(row['keys']) + ',' + str(row['clicks']) + ',' + str(row['impressions']) + ',' + str(row['ctr']) + ',' + str(row['position']) )


def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
    scope=YOUTUBE_UPLOAD_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

  storage = Storage("%s-oauth2.json" % sys.argv[0])
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, args)

  return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))

if __name__ == '__main__':
  main(sys.argv)

サイトが複数ある場合、バッチで
やれると非常に助かります

今度はアナリティクスの方を
取得できるようにしたいです