本教學課程逐步介紹存取 Google Analytics (分析) 帳戶、查詢 Analytics (分析) API、處理 API 回應,並輸出結果的必要步驟。本教學課程使用 Core Reporting API 3.0 版、Management API v3.0 和 OAuth2.0。
步驟 1:啟用 Analytics (分析) API
如要開始使用 Google Analytics API,請先使用設定工具,這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。
建立用戶端 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 套件內含的 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
的值替換為 Play 管理中心的適當值。
"""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:執行範例
啟用 Analytics API 後, 已安裝 Python 適用的 Google API 用戶端程式庫, 然後設定可執行範例的原始碼。
使用下列指令執行範例:
python HelloAnalytics.py
完成這些步驟後,範例會輸出授權使用者的第一個 Google Analytics (分析) 資料檢視 (設定檔) 名稱,以及最近七天的工作階段數。
現在,您可以使用已授權的 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