UrlFetchApp 未连接到 public URL

UrlFetchApp not connecting to public URL

我正在尝试使用在“操作”>“下载”>“CSV

下找到的下载 CSV link 从该网站提取数据

https://app.udot.utah.gov/apex/eom/f?p=288:300

我一直在 UrlFetchApp 行收到错误 302,我不明白为什么。我 运行 带有 httpexception 的记录器并收到无法连接到服务器的错误。该网站 public 并且无论网络如何都可以访问,所以我很难理解发生了什么。 URL 似乎在手动输入时下载 CSV,但我无法让 UrlFetchApp 获取它。

var EquipUrl = "https://app.udot.utah.gov/apex/eom/f?p=288:300:::CSV";
var EquipContent = UrlFetchApp.fetch(EquipUrl).getContentText();
var EquipData = Utilities.parseCsv(EquipContent);

如有任何帮助,我们将不胜感激!

我只是根据评论中的建议尝试了以下操作,结果相同,错误 302。我还尝试将重定向设置为 false,这会以一个空的 EquipData 数组

继续并结束
var options = {
'followRedirects' :true
];
var EquipUrl = "https://app.udot.utah.gov/apex/eom/f?p=288:300:::CSV::::";
var EquipContent = UrlFetchApp.fetch(EquipUrl, options).getContentText();
var EquipData = Utilities.parseCsv(EquipContent);

感谢TheMaster到目前为止的帮助!我在评论中说过,代码在 var cookies 行上吐出一个错误,但该错误已自行纠正,所以我认为它可能是我的代码的错误副本。现在的问题是最后的 Logger 行吐出一个 "Could not parse text" 错误。

function fetchUrlWithCookie() {
  var url = 'https://app.udot.utah.gov/apex/eom/f?p=288:300:::CSV';
  var response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    followRedirects: false,
  });
  var cookie = response.getAllHeaders()['Set-Cookie'];
  response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    headers: {
      Cookie: cookie, //send the cookie we got as header
    },
  });
  Logger.log(Utilities.parseCsv(response.getContentText()));//parseCSV
}

我尝试了几个不同的选项,比如之前尝试登录以查看是否可以找到任何东西。我可以从 Stackdriver 日志记录中提取任何有助于识别问题的信息吗?

非常感谢TheMaster!有效!如果您能发表评论并解决您的问题解决过程,我会很高兴,这样我可以帮助了解下次发生这种情况时要注意什么,但我知道这要求很多。

  var url = 'https://app.udot.utah.gov/apex/eom/f?p=288:300::CSV::::';
  var response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    followRedirects: true,
  });
  var cookie = response.getAllHeaders()['Set-Cookie']; 
  response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    headers: {
      Cookie: cookie, //send the cookie we got as headerw
    },
  });
  Logger.log(Utilities.parseCsv(response.getContentText()));//parseCSV

这是完整功能的代码副本。再次感谢您在这几天的帮助下解决了这个问题。

要点:

一些网站使用 cookies 来维护状态、会话和完成请求。由于 urlFetch 在服务器端而不是在浏览器中运行,因此不会跨请求维护 cookie。但是,我们可以在第一次请求中手动获取cookie,并在后续请求中发送。

代码片段:

function fetchUrlWithCookie() {
  var url = 'xxxx'; //Your csv url
  var response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    followRedirects: false,
  });
  var cookie = response.getAllHeaders()['Set-Cookie']; //Get cookie from header 
  response = UrlFetchApp.fetch(url, {
    muteHttpExceptions: true,
    headers: {
      Cookie: cookie, //send the cookie we got as header
    },
  });
  Logger.log(Utilities.parseCsv(response.getContentText()));//parseCSV
}

参考文献: