首页 > 解决方案 > UrlFetchApp 未连接到公共 URL

问题描述

我正在尝试使用 Actions > Download > CSV 下的下载 CSV 链接从该网站提取数据

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

我在 UrlFetchApp 行上始终收到错误 302,但我不明白为什么。我使用 httpexception 运行记录器并收到无法连接到服务器的错误。无论网络如何,该网站都是公开且可访问的,因此我很难理解发生了什么。手动输入时,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 行吐出“无法解析文本”错误。

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 日志中提取任何有助于识别问题的信息吗?

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

  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

那是功能齐全的代码副本。再次感谢您在这几天内为解决此问题提供的帮助。

标签: cookiesgoogle-apps-scripthttp-status-code-302urlfetch

解决方案


关键点:

一些网站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
}

参考:


推荐阅读