本教程详细介绍了访问 Google Analytics(分析)账号、查询 Google Analytics(分析)API、处理 API 响应和输出结果所需的步骤。本教程使用了 Core Reporting API v3.0、Management API v3.0 和 OAuth2.0。
第 1 步:启用 Google Analytics(分析)API
要开始使用 Google Analytics(分析)API,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目,启用 API 以及创建凭据。
创建客户端 ID
- 打开服务账号页面。如果看到提示,请选择项目。
- 点击 创建服务账号,并输入服务账号的名称和说明。您可以使用默认服务账号 ID,也可以选择其他唯一的账号 ID。完成后,点击创建。
- 后面的服务账号权限(可选)部分无需设置。点击继续。
- 在向用户授予访问此服务账号的权限屏幕上,向下滚动到创建密钥部分。点击 创建密钥。
- 在随即显示的侧面板中,选择密钥的格式:建议使用 JSON。
- 点击创建。您的新公钥/私钥对随后会生成并下载到您的计算机上;该密钥仅此一份。要了解如何安全地存储密钥,请参阅管理服务账号密钥。
- 点击私钥已保存到您的计算机对话框中的关闭,然后点击完成以返回服务账号表格。
将服务账号添加到 Google Analytics(分析)账号中
新创建的服务账号将有一个电子邮件地址 <projectId>-<uniqueId>@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
的文件,其中将包含给定的示例代码。
- 将以下源代码复制或
下载到
HelloAnalytics.py
。 - 将之前下载的
client_secrets.json
移到示例代码所在的目录中。 - 将
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
系统环境变量中:
-
使用以下命令确定 pip 的安装位置:
pip show six | grep "Location:" | cut -d " " -f2
-
将以下代码行添加到
~/.bashrc
文件中,并将<pip_install_path>
替换为上面确定的值:export PYTHONPATH=$PYTHONPATH:<pip_install_path>
-
使用以下命令,在任何已打开的终端窗口中重新加载
~/.bashrc
文件:source ~/.bashrc