Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. from googleapiclient.discovery import build
  2. from oauth2client.service_account import ServiceAccountCredentials
  3. from datetime import date, timedelta, datetime
  4. import csv
  5.  
  6.  
  7. def get_service(api_name, api_version, scopes, key_file_location):
  8.     credentials = ServiceAccountCredentials.from_json_keyfile_name(
  9.         key_file_location, scopes=scopes
  10.     )
  11.  
  12.     # Build the service object.data
  13.     service = build(api_name, api_version, credentials=credentials)
  14.  
  15.     return service
  16.  
  17.  
  18. def get_results(service, profile_id):
  19.     # Use the Analytics Service Object to query the Core Reporting API
  20.     # for the number of sessions within the past seven days.
  21.     return service.data().mcf().get(
  22.         ids='ga:' + '201492804',  # start_date = '2019-10-13',
  23.         start_date='2019-10-01',
  24.         end_date='2019-10-13',
  25.         metrics='mcf:firstInteractionConversions',
  26.         # dimensions = 'mcf:conversionDate,mcf:source,mcf:sourceMedium,mcf:campaignName,mcf:adwordsAdContent,mcf:basicChannelGrouping',
  27.         dimensions='mcf:sourceMediumPath',  # sort = 'mcf:conversionDate',
  28.         filters='mcf:conversionGoalNumber==020',
  29.         max_results='5000'
  30.     ).execute()
  31.  
  32.  
  33. def print_results(results):
  34.     if not results.get('rows', []):
  35.         return
  36.  
  37.     for row in results.get('rows'):
  38.         res = ','.join([get_value(i) for i in row])
  39.         print(res)
  40.  
  41.  
  42. def get_value(obj: dict):
  43.     if 'nodeValue' in obj:
  44.         return obj['nodeValue']
  45.     elif 'primitiveValue' in obj:
  46.         return obj['primitiveValue']
  47.     elif 'conversionPathValue' in obj:
  48.         return ' > '.join([get_value(i) for i in obj['conversionPathValue']])
  49.     else:
  50.         return ''
  51.  
  52.  
  53. def main():
  54.     # Define the auth scopes to request.
  55.     scope = 'https://www.googleapis.com/auth/analytics.readonly'
  56.     key_file_location = 'C:\\Users\\этикет по Китикету\\Downloads\\BBDO-Digital-Console-1074d9efc275.json'
  57.  
  58.     # Authenticate and construct service.
  59.     service = get_service(
  60.         api_name='analytics',
  61.         api_version='v3',
  62.         scopes=[scope],
  63.         key_file_location=key_file_location)
  64.  
  65.     profile_id = '201492804'
  66.  
  67.     print_results(get_results(service, profile_id))
  68.  
  69.  
  70. if __name__ == '__main__':
  71.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement