我正在尝试使用谷歌应用程序脚本和谷歌工作表,基本上是每次NHL球队比赛时自动更新统计信息的谷歌工作表。如何在Google Apps Scripts环境中查询nhl.com online数据库?例如,我感兴趣的统计数据是某个团队的总分。如何从Google Apps Scripts中的nhl.com获取整数值?
发布于 2017-10-30 05:50:12
您需要使用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
}
如果您需要定期运行此函数,则需要设置一个时间驱动触发器,如here所述。
更新:在你的评论之后,有第二部分。一开始,我假设nhl.com有某种可以返回JSON格式的响应的API,但事实并非如此。这就是为什么你会在JSON.parse上得到这个错误--返回的结果不是一个JSON对象,而是一个超文本标记语言网页。
因此,您的任务变得更加棘手:您可以尝试抓取页面并从html中获取结果,或者使用第三方API,如MySportFeeds。您还可以看到此Quora discussion。
如果你使用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个选择:
使用最后一个选项,代码如下所示:
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
https://stackoverflow.com/questions/47006777
复制相似问题