Hello Analytics API:已安裝應用程式的 Python 快速入門導覽課程

本教學課程逐步介紹存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應,並輸出結果的必要步驟。本教學課程使用 Core Reporting API 3.0 版Management API v3.0OAuth2.0

步驟 1:啟用 Analytics (分析) API

如要開始使用 Google Analytics API,請先使用設定工具,這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

建立用戶端 ID

在「憑證」頁面中:

  1. 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」
  2. 在「APPLICATION TYPE」中選取「其他」
  3. 輸入憑證名稱。
  4. 點選「建立」

選取您剛剛建立的憑證,然後按一下「Download JSON」(下載 JSON)。將下載的檔案儲存為 client_secrets.json,稍後用於教學課程。

步驟 2:安裝 Google 用戶端程式庫

您可以使用套件管理員,或是手動下載並安裝 Python 用戶端程式庫:

pip

使用 pip,這是安裝 Python 套件的建議工具:

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

設定工具

使用 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:執行範例

啟用 Analytics API 後, 已安裝 Python 適用的 Google API 用戶端程式庫, 然後設定可執行範例的原始碼。

使用下列指令執行範例:

python HelloAnalytics.py
  1. 應用程式會在瀏覽器中載入授權頁面。
  2. 如果您尚未登入 Google 帳戶,系統會提示您登入。如果您登入多個 Google 帳戶,系統會要求您選取其中一個帳戶進行授權。

完成這些步驟後,範例會輸出授權使用者的第一個 Google Analytics (分析) 資料檢視 (設定檔) 名稱,以及最近七天的工作階段數。

現在,您可以使用已授權的 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