testga.py
# -*- coding: utf-8 -*-
# Google Analytics API
import yaml
import datetime
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import argparse
CLIENT_SECRETS = 'client_secrets.json'
# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/analytics.readonly',
message='%s is missing' % CLIENT_SECRETS
)
# A file to store the access token
TOKEN_FILE_NAME = 'credentials.dat'
def prepare_credentials():
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
# Retrieve existing credendials
storage = Storage(TOKEN_FILE_NAME)
credentials = storage.get()
# If no credentials exist, we create new ones
if credentials is None or credentials.invalid:
credentials = tools.run_flow(FLOW, storage, flags)
return credentials
def initialize_service():
http = httplib2.Http()
credentials = prepare_credentials()
http = credentials.authorize(http)
return build('analytics', 'v3', http=http)
#API-Ausführung(core API)
def get_ga_data(service, profile_id, start_date, end_date):
ids = "ga:" + profile_id
metrics = "ga:pageviews"
dimensions = "ga:Year,ga:month,ga:day,ga:pagetitle"
filter = "ga:pageviews>=100"
data = service.data().ga().get(
ids=ids, start_date=start_date, end_date=end_date, metrics=metrics,
dimensions=dimensions, filters=filter).execute()
return data
# main
if __name__ == '__main__':
service = initialize_service()
profile_id = "12345678" #Profil-ID der Zielwebsite
start_date = "2017-01-01"
end_date = "2017-01-10"
data = get_ga_data(service, profile_id, start_date, end_date)
row = data["rows"]
nm = ['ga_year','ga_month','ga_day','ga_pageTitle','ga_pageviews']
lst = []
for i in row:
d = dict(zip(nm,i))
lst.append(d)
print(lst)
print("finish!")
Recommended Posts