Google AnalyticsAPI不会产生自定义细分

时间:2017-04-18 17:28:50

标签: python google-analytics

我正在使用Python脚本从Google Analytics获取细分信息。 Google Analytics附带的所有内置细分均可正常打印,但我创建的自定义细分未显示。

以下是脚本的相关部分:

def get_service(api_name, api_version, scope, key_file_location,
                service_account_email):
  """Get a service that communicates to a Google API.

  Args:
    api_name: The name of the api to connect to.
    api_version: The api version to connect to.
    scope: A list auth scopes to authorize for the application.
    key_file_location: The path to a valid service account p12 key file.
    service_account_email: The service account email address.

  Returns:
    A service that is connected to the specified API.
  """

  credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)

  http = credentials.authorize(httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service


def get_segments(service):

    try:
      segments = service.management().segments().list().execute()

    except TypeError, error:
        # Handle errors in constructing a query.
        print 'There was an error in constructing your query : %s' % error

    except HttpError, error:
        # Handle API errors.
        print ('There was an API error : %s : %s' %(error.resp.status, error.resp.reason))

    # Example #2:
    # The results of the list method are stored in the segments object.
    # The following code shows how to iterate through them.
    for segment in segments.get('items', []):
      print 'Segment Id         = %s' % segment.get('id')
      print 'Segment kind       = %s' % segment.get('kind')
      print 'Segment segmentId  = %s' % segment.get('segmentId')
      print 'Segment Name       = %s' % segment.get('name')
      print 'Segment Definition = %s' % segment.get('definition')
      if segment.get('created'):
        print 'Created    = %s' % segment.get('created')
        print 'Updated    = %s' % segment.get('updated')
      print

def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Use the developer console and replace the values with your
  # service account email and relative location of your key file.
  service_account_email = '************'
  key_file_location = '*********'

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, key_file_location,
    service_account_email)

  get_segments(service)


if __name__ == '__main__':
  main()

1 个答案:

答案 0 :(得分:0)

您需要为已创建的自定义细分

启用协作权限

Manage Segments#Set Segment availability

访问此链接并转到那里的“设置细分可用性”部分。 应用“协作权限”选项,如链接中所示。

在此之后,您的细分受众群将从您发布的API代码中提取;)

请注意: Analytics Core Reporting API无权访问自定义细分。它们只能由Analytics Management API

访问