【问题标题】:Google Script UrlFetchApp.fetch returns a 404 eventhough the page exist即使页面存在,Google Script UrlFetchApp.fetch 也会返回 404
【发布时间】:2015-09-09 10:49:06
【问题描述】:

我正在发送带有 Google 电子表格和 Google 脚本的自动报告。

到目前为止,它运行良好。但不知何故,当我尝试创建要通过电子邮件发送的新报告时,函数“UrlFetchApp.fetch”返回 404。当我尝试复制旧报告时发生了同样的情况。

带有“UrlFetchApp.fetch”的行给了我这个错误:

https://docs.google.com/spreadsheets/d/1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8/pub?gid=195635557&single=true&output=pdf 的请求失败,返回代码 404。服务器响应被截断

看来我不是唯一遇到问题的人,但我找不到任何解决方案。

代码如下:

function emailSpreadsheetAsCSV() {
  var ss = SpreadsheetApp.openById("1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8");
  var url = ss.getUrl();
  url = url.replace(/edit$/,'');     
  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets(); 
  //make an empty array to hold your fetched blobs  
  var blobs = [];
  for (var i=0; i<sheets.length; i++) {
      var response = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8/pub?gid=195635557&single=true&output=pdf", {
        headers: {
          'Authorization': 'Bearer ' +  token
        },
        'muteHttpExceptions': false
      });
    //convert the response to a blob and store in our array
    blobs[i] = response.getBlob().setName(sheets[i].getName() + '.csv');
  }
  //create new blob that is a zip file containing our blob array
  var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');     
return blobs[0];       
}

非常感谢您的帮助。

艾美式。

【问题讨论】:

标签: google-apps-script google-docs


【解决方案1】:

我也遇到了这个问题,经过一番研究,Spence Easton(问题 34573295)解决了我的问题。我只是将这个虚假调用添加到驱动器,以便授予访问权限,因此脚本现在可以访问您的文件。 在尝试获取 url 之前将其添加到顶部附近:

var bogus = DriveApp.getRootFolder();

现在它运行良好,没有 404 错误。

【讨论】:

    【解决方案2】:

    从请求中删除标头:

    var response = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/1qm_bCKn4MbLKy7AIuIeu7bTZcTk8ObYBln0GAxwfsX8/pub?gid=195635557&single=true&output=pdf", {
    
            'muteHttpExceptions': false
          });
    

    检查它是否适合你。

    【讨论】:

      【解决方案3】:

      您使用“pub”网址,所以您确定电子表格已在网络上发布?如果您收到 404,则表示该页面未发布。 如果文件已发布,则不需要承载,因为它现在是公开的。

      在我不太了解您的代码之后,因为您迭代了文件的所有工作表

      for (var i=0; i<sheets.length; i++)
      

      但是 urlfetch 中的 url 的参数“gid” (pub?gid=195635557&single=true&output=pdf) 是固定的?

      第二点,您将文件作为 pdf 并在创建 csv 之后获得?

      为什么不直接将文件作为 csv 获取:https://docs.google.com/spreadsheets/export?id=TheIdOfTheFile&exportFormat=csv

      通过修改此代码,您可以直接获取 csv,请参阅:https://stackoverflow.com/a/28503601/3556215

      注意你会得到第一页而不是其他页面。

      史蒂芬

      【讨论】:

        【解决方案4】:

        尝试:

        var response = UrlFetchApp.fetch(url, options);
        var result = JSON.parse(res.getContentText());
        

        【讨论】:

          猜你喜欢
          • 2019-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-16
          • 2018-08-20
          • 1970-01-01
          • 2017-03-20
          • 1970-01-01
          相关资源
          最近更新 更多