繁体   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