在 Google 試算表中自動存取 Google Analytics (分析) 資料

Google Analytics (分析) API 團隊 Nick Mihailovski - 2012 年 8 月

本教學課程說明如何使用 Apps Script 在 Google 試算表中存取 Management 和 Core Reporting API。


簡介

您可以使用 Google Analytics APIGoogle Apps Script,透過 Google 試算表存取 Google Analytics (分析) 資料。這項功能強大的功能可讓您運用 Google 試算表的所有強大功能處理數據分析資料,例如簡單的共用、協作、圖表製作和視覺化工具。

本教學課程將逐步引導您使用 Google Apps Script,在 Google 試算表中存取 Google Analytics (分析) 資料所需的程式碼。

總覽

本教學課程說明如何註冊及設定 Apps Script 環境,以便使用 Google Analytics (分析) API。設定完成後,教學課程會逐步引導您使用 Management API 擷取授權使用者的資料檢視 (設定檔) ID。接著,如何使用資料檢視 (設定檔) ID 查詢 Core Reporting API,從 Google 擷取前 250 名行動搜尋關鍵字。最後會將結果插入 Google 試算表中。取得資料後,本教學課程也會討論如何自動擷取資料。

使用 Google Analytics (分析) API 和 Apps Script 建構應用程式時,您通常會完成下列步驟:

  • 在 Google 試算表中啟用 Google Analytics (分析) API
  • 使用 Google Analytics (分析) API

以下將詳細說明每個步驟。

在 Apps Script 中啟用 Google Analytics API

如要在 Google 試算表中存取 Google Analytics (分析) 資料,請按照下列步驟操作:

  1. 建立 Google 試算表檔案。為它取個酷炫的名稱。
  2. 建立新的 Apps Script。
    1. 在選單中依序點選「擴充功能」>「Apps Script」
    2. 如果系統彈出選單,只要按一下「Blank Project」即可。
    3. 為專案命名。請確定名稱很酷。

建立新指令碼後,請務必啟用 Google Analytics (分析) 服務

  1. 在指令碼編輯器中,依序選取「Resources」(資源) >「Advanced Google services」(進階 Google 服務...)
  2. 在出現的對話方塊中,按一下 Google Analytics (分析) API 旁的「開啟/關閉」切換按鈕。
  3. 在對話方塊底部,按一下 Google Developers Console 的連結。
  4. 在新版控制台中,再次按一下 Google Analytics (分析) API 旁邊的「開啟/關閉」切換按鈕。(啟用後,即可跳至頁面頂端)。
  5. 返回指令碼編輯器,然後按一下對話方塊中的「OK」

畫面上會出現一個黃色的小對話方塊,指出您已成功在指令碼中加入新的 Google API 服務。您現在可以開始編寫第一個指令碼。

使用 Google Analytics (分析) API

本教學課程中的指令碼會查詢 Google Analytics (分析) API 中的前 250 個 Google 行動搜尋關鍵字,然後將結果輸出至 Google 試算表。為完成這項作業,指令碼會按照下列步驟操作:

  • 擷取授權使用者的第一個檢視畫面 (個人資料)。
  • 透過 Core Reporting API 查詢資料。
  • 在試算表中插入資料。

將下列函式新增至空白專案。

function runDemo() {
  try {

    var firstProfile = getFirstProfile();
    var results = getReportDataForProfile(firstProfile);
    outputToSpreadsheet(results);

  } catch(error) {
    Browser.msgBox(error.message);
  }
}

在上述程式碼中,try...catch 區塊是用於處理任何 API 錯誤。如果發生任何錯誤,程式會停止執行作業,並在訊息方塊中顯示錯誤。在 try 區塊中,函式可用來執行指令碼會經歷的各個步驟。現在,讓我們為這些函式新增程式碼。

擷取授權使用者的第一個資料檢視 (設定檔)

在 Google Analytics (分析) 中,每份報表都屬於一個資料檢視 (設定檔),並以資料檢視 (設定檔) ID 表示。因此,當您指定報表資料的查詢時,也必須指定要從中擷取資料的資料檢視 (設定檔) ID。

Google Analytics Management API 可讓您存取屬於使用者的所有帳戶、網站資源和資料檢視 (設定檔) 實體。這些實體都屬於階層結構中,您可以透過程式輔助方式掃遍這個階層,擷取授權使用者的資料檢視 (個人資料) ID。

我們編寫的第二個函式會掃遍 Management API 階層,並傳回使用者的第一個檢視畫面 (設定檔)。複製下列程式碼並貼到 Apps Script 專案:

function getFirstProfile() {
  var accounts = Analytics.Management.Accounts.list();
  if (accounts.getItems()) {
    var firstAccountId = accounts.getItems()[0].getId();

    var webProperties = Analytics.Management.Webproperties.list(firstAccountId);
    if (webProperties.getItems()) {

      var firstWebPropertyId = webProperties.getItems()[0].getId();
      var profiles = Analytics.Management.Profiles.list(firstAccountId, firstWebPropertyId);

      if (profiles.getItems()) {
        var firstProfile = profiles.getItems()[0];
        return firstProfile;

      } else {
        throw new Error('No views (profiles) found.');
      }
    } else {
      throw new Error('No webproperties found.');
    }
  } else {
    throw new Error('No accounts found.');
  }
}

在這個函式中,系統會先使用 Analytics.Management.Accounts.list 方法查詢帳戶集合。如果授權使用者擁有 Google Analytics (分析) 帳戶,系統會擷取第一個帳戶的 ID。接著,呼叫 Analytics.Management.Webproperties.list 方法並傳遞在上一個步驟中擷取的帳戶 ID 方法,即可查詢網站資源集合。如果有網站資源,系統最終會使用 Analytics.Management.Profiles.list 方法查詢檢視畫面 (設定檔) 集合。帳戶 ID 和網站資源 ID 都會以參數的形式傳遞給此方法。如果有資料檢視 (設定檔),就會傳回第一個資料檢視 (設定檔)。

如果 API 錯誤發生時,或是 API 回應未包含任何結果,系統會擲回錯誤,並提供說明找不到任何結果的訊息。上述 runDemo 函式中的 catch 區塊會擷取這項錯誤,並將訊息列印給使用者。

指令碼傳回後,就可以查詢報表資料。

透過 Core Reporting API 查詢資料。

取得資料檢視 (設定檔) ID 後,請使用 Core Reporting API 查詢 Google Analytics (分析) 報表資料。在本節中,您將瞭解如何使用 Apps Script 查詢這個 API。

將下列程式碼加進 Apps Script 專案:

function getReportDataForProfile(firstProfile) {

  var profileId = firstProfile.getId();
  var tableId = 'ga:' + profileId;
  var startDate = getLastNdays(14);   // 2 weeks (a fortnight) ago.
  var endDate = getLastNdays(0);      // Today.

  var optArgs = {
    'dimensions': 'ga:keyword',              // Comma separated list of dimensions.
    'sort': '-ga:sessions,ga:keyword',       // Sort by sessions descending, then keyword.
    'segment': 'dynamic::ga:isMobile==Yes',  // Process only mobile traffic.
    'filters': 'ga:source==google',          // Display only google traffic.
    'start-index': '1',
    'max-results': '250'                     // Display the first 250 results.
  };

  // Make a request to the API.
  var results = Analytics.Data.Ga.get(
      tableId,                    // Table id (format ga:xxxxxx).
      startDate,                  // Start-date (format yyyy-MM-dd).
      endDate,                    // End-date (format yyyy-MM-dd).
      'ga:sessions,ga:pageviews', // Comma seperated list of metrics.
      optArgs);

  if (results.getRows()) {
    return results;

  } else {
    throw new Error('No views (profiles) found');
  }
}

function getLastNdays(nDaysAgo) {
  var today = new Date();
  var before = new Date();
  before.setDate(today.getDate() - nDaysAgo);
  return Utilities.formatDate(before, 'GMT', 'yyyy-MM-dd');
}

程式碼的第一部分使用 Analytics.Data.Ga.get 方法建構 Core Reporting API 查詢。此方法接受一組參數,用於指定要擷取的報表類型。每項 Core Reporting API 查詢都是由一組必要和選用參數組成。必要參數會以參數的形式傳遞至方法,而選用的參數則會以物件的形式傳遞。

table ID 是必要參數,由將前置字串 ga: 編譯為資料檢視 (設定檔) ID 後所構成。程式碼會使用在上一個步驟中擷取到的資料檢視 (設定檔) ID 建立資料表 ID。也需要開始和結束日期,並指定擷取資料的日期範圍。兩者皆使用 getLastNdays 函式根據今天的日期計算。最後,所有選用參數都會使用 optArgs 物件傳遞至函式。

Analytics.Data.Ga.get 方法執行時,系統會向 Core Reporting API 發出要求。如果發生錯誤,系統會在外部 runDemo 方法中定義的 try...catch 區塊擷取錯誤。如果要求成功,則會傳回結果。

在試算表中插入資料

指令碼中的最後一個步驟是將 Core Reporting API 的結果輸出至 Google 試算表。outputToSpreadsheet 方法可執行這項作業。在專案中新增下列程式碼:

function outputToSpreadsheet(results) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet();

  // Print the headers.
  var headerNames = [];
  for (var i = 0, header; header = results.getColumnHeaders()[i]; ++i) {
    headerNames.push(header.getName());
  }
  sheet.getRange(1, 1, 1, headerNames.length)
      .setValues([headerNames]);

  // Print the rows of data.
  sheet.getRange(2, 1, results.getRows().length, headerNames.length)
      .setValues(results.getRows());
}

這個函式會先將新工作表插入使用中的試算表。然後將所有標頭和報表資料插入工作表。如需更多將資料插入 Google 試算表的提示,請參閱 將資料儲存到試算表教學課程中的 從 JavaScript 物件將資料寫入試算表

執行指令碼

將所有程式碼新增至專案之後,即可開始執行專案。

  • 在指令碼編輯器工具列的「選取函式」下拉式選單中,選取 runDemo
  • 接著,按一下「play」按鈕。

第一次執行這項作業時,畫面上會出現彈出式視窗,要求您授權這個指令碼存取您的 Google Analytics (分析) 帳戶資料。

按一下「授權」。

點選後,就會開啟由 google.com 代管的新網頁,並提示您授予這個指令碼存取您資料的權限。按一下「允許」之後,系統會將您重新導向至確認頁面。此時,指令碼就可以存取 Google Analytics (分析) 資料,並繼續執行。

指令碼執行後,在 Google 試算表中點選視窗。 您應該會看到從 API 傳回的所有關鍵字資料,或顯示錯誤訊息的訊息方塊。

自動化指令碼

此時,您應該擁有可查詢 Google Analytics (分析) API 的指令碼。您現在可以自動執行這個指令碼,每天晚上擷取新資料。Apps Script 具備 triggers 功能,可讓你輕鬆使用自動化功能。

如要自動執行這個指令碼,請按照下列步驟操作:

  • 在指令碼編輯器工具列中,按一下 Resources -> All your triggers...
  • 按一下 Add a new trigger,畫面上隨即會顯示觸發條件對話方塊。
  • 設定觸發條件在每晚執行 runDemo 方法
    • Run 下拉式選單應設為:runDemo
    • Events 下拉式選單應設為:Time-drivenDay timerMidnight to 1am

設定完畢後,這個指令碼會持續執行每晚執行,並在早晨時提供最新資料。

如果晚上發生任何錯誤,您會想要收到通知。Apps Script 能讓您在發生故障時傳送電子郵件快訊。如要進行設定,請按一下觸發條件對話方塊中的 notifications 連結。畫面上會出現新的對話方塊,供您設定要接收錯誤的電子郵件。

結論

您已成功註冊並授權存取指令碼。您多次查詢 Management API 以擷取資料檢視 (設定檔) ID。接著,您使用資料檢視 (設定檔) ID 查詢 Core Reporting API 來擷取資料,並將資料輸出到 Google 試算表。

您可以使用教學課程中所述的技巧,執行更複雜的分析、獲得更深入的分析結果、建構自訂資訊主頁,以及省下大量手動報表的時間。

以下還有幾個實用的教學課程,能幫助您充分運用 Google Analytics (分析) API 和 Google Apps Script: