Google Analytics(分析)API 入门:适用于已安装应用的 Python 快速入门

本教程详细介绍了访问 Google Analytics(分析)帐户、查询 Google Analytics(分析)API、处理 API 响应和输出结果所需的步骤。本教程使用了 Core Reporting API v3.0Management API v3.0OAuth2.0

第 1 步:启用 Google Analytics(分析)API

要开始使用 Google Analytics(分析)API,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目,启用 API 以及创建凭据。

创建客户端 ID

从“凭据”页:

  1. 点击创建凭据并选择 OAuth 客户端 ID
  2. 对于“应用类型”选择其他
  3. 对凭据命名。
  4. 点击创建

选择您刚刚创建的凭据,然后点击下载 JSON。将下载的文件另存为 client_secrets.json;您会在本教程的后面需要此文件。

第 2 步:安装 Google 客户端库

您既可以使用文件包管理器,也可以手动下载并安装 Python 客户端库:

pip

建议使用 pip 工具来安装 Python 文件包:

sudo pip install --upgrade google-api-python-client

Setuptools

使用 setuptools 文件包中所含的 easy_install 工具:

sudo easy_install --upgrade google-api-python-client

手动安装

下载最新的适用于 Python 的客户端库,然后解压代码并运行:

sudo python setup.py install

您可能需要利用超级用户 (sudo) 权限调用相应命令才能将其安装到系统 Python 上。

第 3 步:设置示例代码

您需要创建一个名为 HelloAnalytics.py 的文件,其中将包含指定的示例代码。

  1. 将以下源代码复制或下载HelloAnalytics.py 中。
  2. 将之前下载的 client_secrets.json 移到示例代码所在的目录中。
"""A simple example of how to access the Google Analytics API."""

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools


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

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      client_secrets_path, scope=scope,
      message=tools.message_if_missing(client_secrets_path))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(api_name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

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

  return service


def get_first_profile_id(service):
  # Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for the authorized user.
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[0].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()

      if profiles.get('items'):
        # return the first view (profile) id.
        return profiles.get('items')[0].get('id')

  return None


def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  # for the number of sessions in the past seven days.
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()


def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'


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

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, 'client_secrets.json')
  profile = get_first_profile_id(service)
  print_results(get_results(service, profile))


if __name__ == '__main__':
  main()

第 4 步:运行示例代码

在您启用了 Google Analytics(分析)API、安装了适用于 Python 的 Google API 客户端库并设置了示例源代码后,该示例代码就可以运行了。

使用以下文件运行示例代码:

python HelloAnalytics.py
  1. 应用将在浏览器中加载授权页面。
  2. 如果您尚未登录自己的 Google 帐户,那么系统会提示您登录。如果您登录了多个 Google 帐户,那么系统会提示您选择一个帐户来用于授权。

当您完成上述步骤后,示例代码就会输出已获授权用户的首个 Google Analytics(分析)数据视图(配置文件)的名称以及过去 7 天内的会话数。

现在,借助已授权的 Google Analytics(分析)服务对象,您可以运行 Management API 参考文档中的任何代码示例。例如,您可以尝试更改代码来使用 accountSummaries.list 方法。

问题排查

AttributeError:'Module_six_moves_urllib_parse' 对象没有 'urlparse' 属性

在 Mac OSX 中,当“six”模块(该库的依赖项)的默认安装先于 pip 安装的模块加载时,就会出现上述错误。要解决该问题,请将 pip 的安装位置添加到 PYTHONPATH 系统环境变量中:

  1. 使用以下命令确定 pip 的安装位置:

    pip show six | grep "Location:" | cut -d " " -f2
    

  2. 将以下命令行添加到您的 ~/.bashrc 文件中,将 <pip_install_path> 替换为上面确定的值:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. 使用以下命令,在任何已打开的终端窗口中重新加载您的 ~/.bashrc 文件:

    source ~/.bashrc