Google Apps 脚本:UrlFetchApp 出现 403 错误

jas*_*son 1 urlfetch google-apps-script

我正在使用谷歌应用程序脚本

var rss = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&CIK=&type=8-k&company=&dateb=&owner=exclude&start=0&count=100&output=atom"
var r = UrlFetchApp.fetch(rss).getContentText()
Run Code Online (Sandbox Code Playgroud)

但有时,我会收到执行失败的消息,这就是响应。大约是一半的时间。

Exception: Request failed for https://www.sec.gov returned code 403. Truncated server response: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w... (use muteHttpExceptions option to examine full response)
Run Code Online (Sandbox Code Playgroud)

不知道为什么会发生以及如何解决它。

Tan*_*ike 5

尽管不幸的是,我无法复制您的情况,例如but once a while, I get a failed execution and this is the response.,按如下方式重试请求怎么样?

示例脚本:

var res = null;
var maxRetries = 5;
var rss = "https://www.sec.gov/cgi-bin/browse-edgar?action=getcurrent&CIK=&type=8-k&company=&dateb=&owner=exclude&start=0&count=100&output=atom";
for (var i = 0; i < maxRetries; i++) {
  res = UrlFetchApp.fetch(rss, {muteHttpExceptions: true});
  if (res.getResponseCode() == 200) break;
  res = null;
  Utilities.sleep(5000);
}
if (!res) throw new Error("Values cannot be retrieved.");

// do something.
var value = res.getContentText();
Run Code Online (Sandbox Code Playgroud)
  • 在此示例脚本中,当状态代码不是 时200,5 秒后将重试请求。并且最大重试次数为5次。
  • 请根据您的实际情况maxRetries进行修改Utilities.sleep(5000)

参考: