【发布时间】:2020-07-09 00:41:03
【问题描述】:
我在 Google 表格中创建了一个脚本,该脚本运行良好,但一段时间后我收到以下错误: 异常:一天服务调用次数过多:urlfetch
我想我一天调用了 200-300 次这个函数,因为我检查过它应该低于限制。
我读到我们可以使用缓存来避免这个问题,但不确定如何在我的代码中使用它。
function scrapercache(url) {
var result = [];
var description;
var options = {
'muteHttpExceptions': true,
'followRedirects': false,
};
var cache = CacheService.getScriptCache();
var properties = PropertiesService.getScriptProperties();
try {
let res = cache.get(url);
if (!res) {
// trim url to prevent (rare) errors
url.toString().trim();
var r = UrlFetchApp.fetch(url, options);
var c = r.getResponseCode();
// check for meta refresh if 200 ok
if (c == 200) {
var html = r.getContentText();
cache.put(url, "cached", 21600);
properties.setProperty(url, html);
var $ = Cheerio.load(html); // make sure this lib is added to your project!
// meta description
if ($('meta[name=description]').attr("content")) {
description = $('meta[name=description]').attr("content").trim();
}
}
result.push([description]);
}
}
catch (error) {
result.push(error.toString());
}
finally {
return result;
}
}
请问如何使用这样的缓存来增强我的脚本?
var cache = CacheService.getScriptCache();
var result = cache.get(url);
if(!result) {
var response = UrlFetchApp.fetch(url);
result = response.getContentText();
cache.put(url, result, 21600);
【问题讨论】:
-
I read we can use cache to avoid this issue你在哪里读到这个?缓存信息与您发出的获取请求的数量无关,因此这本身并不能减轻命中限制。但是,如果您将信息存储在脚本缓存中,则可能不需要每次都进行提取。你怎么打电话给scrapercache(url),url是什么? -
嗨拉法,感谢您的留言。我在这篇文章中读到了关于缓存的信息:stackoverflow.com/questions/46426792/… 我这样调用刮板函数:``` =value(left(REGEXEXTRACT(scraper("gurufocus.com/term/fscore/…),".as."),1)) ``` 我可能有 200 个这样的单元格,所以也许他们调用 URLfetch 的次数太多了,所以在获取数据后将数据存储在缓存中会很好。你知道如何在我的函数中包含缓存元素吗? ? 谢谢
标签: caching google-apps-script google-sheets urlfetch