Advertisement
Shojib_Mahabub

Untitled

Oct 11th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.59 KB | None | 0 0
  1. from apiclient.discovery import build
  2. from oauth2client.service_account import ServiceAccountCredentials
  3. import pandas as pd
  4. from pandas.io.json import json_normalize
  5.  
  6. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  7. KEY_FILE_LOCATION = './key.json'
  8. VIEW_ID = #secret
  9.  
  10.  
  11. def initialize_analyticsreporting():
  12.   credentials = ServiceAccountCredentials.from_json_keyfile_name(
  13.       KEY_FILE_LOCATION, SCOPES)
  14.  
  15.   # Build the service object.
  16.   analytics = build('analyticsreporting', 'v4', credentials=credentials)
  17.  
  18.   return analytics
  19.  
  20.  
  21. def get_report(analytics):
  22.   return analytics.reports().batchGet(
  23.       body={
  24.         'reportRequests': [
  25.             {
  26.             'viewId': VIEW_ID,
  27.             'dateRanges': [{'startDate': '2019-09-28', 'endDate': 'today'}],
  28.             'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:pageViews'}],
  29.             'dimensions': [
  30.                     {'name': 'ga:date'},
  31.                     {'name': 'ga:pagePath'},
  32.                     {'name': 'ga:channelGrouping'},
  33.                     {'name': 'ga:medium'},
  34.                     {'name': 'ga:source'},
  35.                     {'name': 'ga:referralPath'},
  36.                     {'name': 'ga:fullReferrer'}
  37.                 ]
  38.             }
  39.         ]
  40.       }
  41.   ).execute()
  42.  
  43. def parse_data(response):
  44.   reports = response['reports'][0]
  45.   columnHeader = reports['columnHeader']['dimensions']
  46.   metricHeader = reports['columnHeader']['metricHeader']['metricHeaderEntries']
  47.  
  48.   columns = columnHeader
  49.   for metric in metricHeader:
  50.     columns.append(metric['name'])
  51.  
  52.   data = json_normalize(reports['data']['rows'])
  53.   data_dimensions = pd.DataFrame(data['dimensions'].tolist())
  54.   data_metrics = pd.DataFrame(data['metrics'].tolist())
  55.   data_metrics = data_metrics.applymap(lambda x: x['values'])
  56.   data_metrics = pd.DataFrame(data_metrics[0].tolist())
  57.   result = pd.concat([data_dimensions, data_metrics], axis=1, ignore_index=True)
  58.  
  59.   return result
  60.  
  61.  
  62. def main():
  63.   analytics = initialize_analyticsreporting()
  64.   response = get_report(analytics)
  65.   parse_data(response).to_csv('file.csv', encoding = 'utf-8')
  66.  
  67. if __name__ == '__main__':
  68.   main()
  69.  
  70.  
  71. """
  72. expected result
  73. Referral Path   Full Referrer   Source      Medium      Page    Date            Channel Grouping    Sessions    Pageviews
  74. (not set)       (direct)        (direct)    (none)      /       Sep 29, 2019    Direct              0           5
  75. (not set)       (direct)        (direct)    (none)      /       Sep 30, 2019    Direct              6           8
  76.  
  77. current result [I want headers to change like expected]
  78.     0           1   2               3       4       5           6       7   8
  79. 0   20190928    /   Organic Search  organic google  (not set)   google  4   6
  80. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement