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. 打开服务帐号。如果看到相关提示,请选择项目。
  2. 点击创建服务帐号
  3. 创建服务帐号窗口中,键入服务帐号的名称,然后选择提供新的私钥。如果您希望将 Google Workspace 全网域权限授予该服务帐号,另请选中启用 Google Workspace 全网域委派功能。然后点击保存

您的新公钥/私钥对已生成并下载到您的计算机;该密钥仅此一份,您负责安全存储该密钥

将服务帐号添加到 Google Analytics(分析)帐号中

新建服务帐户的电子邮件地址为 &ltprojectId&gt-&ltuniqueId&gt@developer.gserviceaccount.com,可用于向您想通过该 API 访问的 Google Analytics(分析)帐户添加用户。就本教程涵盖的内容而言,只需阅读和分析权限即可。

第 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 移到示例代码所在的目录中。
  3. key_file_location 的值替换为 Developers Console 中的相应值。
"""A simple example of how to access the Google Analytics API."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def get_service(api_name, api_version, scopes, key_file_location):
    """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.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

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

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

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

    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 this 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 within 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):', results.get('profileInfo').get('profileName')
        print 'Total Sessions:', 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'
    key_file_location = '<REPLACE_WITH_JSON_FILE>'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    print_results(get_results(service, profile_id))

if __name__ == '__main__':
    main()

第 4 步:运行示例代码

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

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

python HelloAnalytics.py

当您完成上述步骤后,示例代码就会输出已获授权用户的首个 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