簡體   English   中英

如何在Google Apps腳本中從在線數據庫查詢?

[英]How to query from an online database in Google Apps Scripts?

我正在嘗試使用Google Apps腳本和Google工作表來基本上在每次NHL團隊參加比賽時自動使用統計信息更新Google工作表。 如何在Google Apps腳本環境中查詢nhl.com在線數據庫? 例如,我感興趣的統計數據是特定團隊的總積分。 如何在Google Apps腳本中從nhl.com獲取該整數值?

您需要使用GAS的服務UrlFetchApp發送http請求並接受響應。

您的代碼可能類似於:

 function getMatchResults() {
    var options = {
        'method': 'get',
        //and any other additional parameters you might need
    };
    var url = 'http://www.nhl.com/stats/team?aggregate=0&gameType=2&report=teamsummary&teamId=24&reportType=season&seasonFrom=20172018&seasonTo=20172018&filter=gamesPlayed,gte,1&sort=points%22'
    var results = UrlFetchApp.fetch(url, options); 
    Logger.log(results);
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    //further on goes your code to actually save the results into your sheet
}

如果您需要此功能,定期運行,你需要設置其描述時間驅動的觸發位置

更新:在您發表評論后,還有第二部分。 最初,我假設nhl.com具有某種API,該API會以JSON格式返回響應,但事實並非如此。 這就是為什么在JSON.parse處出現錯誤的原因-返回的結果不是JSON對象,而是HTML網頁。

因此,您的任務變得更加棘手:您嘗試抓取頁面並從html中獲取結果,或者使用MySportFeeds之類的第三方API。 您也可以查看Quora討論

如果您使用MySportFeeds(似乎免費供個人使用),則上述功能可能類似於:

function getMatchResults() {
  var headers = {
    'Authorization': 'username:password',
  };
  var options = {
    'method': 'get',
    'headers': headers,
    //and any other additional parameters you might need
  };
  var url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/scoreboard.json?fordate=20161211'
  var results = UrlFetchApp.fetch(url, options); 
  Logger.log(results);
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //further on goes your code to actually save the results into your sheet
}

更新#2:

每發表一則評論:)實際上,您有3個選擇:

  • 刮整個頁面(有關內容,請參閱Wikipedia文章 此處
  • 使用一些第三方API(上面的MySportFeeds)
  • 查看頁面源並查找從何處加載數據—有關更多詳細信息,請參見此答案

使用最后一個選項,代碼如下所示:

function getMatchResults() {
  var headers = {
    "Origin": "http://http://www.nhl.com/"
  };
  var options = {
    'method': 'get',
    //and any other additional parameters you might need
  };
  var baseUrl = 'http://www.nhl.com/stats/rest/individual/team/basic/game/teamsummary'
  var urlParameters = '?cayenneExp=teamId=23';
  var url = baseUrl + urlParameters;
  var results = UrlFetchApp.fetch(url, options); 
  Logger.log(results);
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //further on goes your code to actually save the results into your sheet
}

您可以在此處看到http://www.nhl.com/stats/rest/individual/team/basic/game/teamsummary?cayenneExp=返回的統計信息,並且在cayenneExp參數中應指定其他設置(例如teamId = 23(在示例中為溫哥華)。 這是在devtools中的外觀: http : //take.ms/fSH7H

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM