使用UrlFetchApp访问mots.go.th域名时出现DNS错误问题排查
更新:发现使用UrlFetchApp访问整个https://www.mots.go.th域名都会出现DNS错误,并非仅针对特定页面,这可能是反爬保护机制?
尝试使用Google Apps Script的UrlFetchApp命令从网站链接提取Excel文件(该链接可在浏览器中正常点击下载),目标URL为:https://www.mots.go.th/images/v2022_1741001884711RmViLTIwMjVQLnhsc3g=.xlsx
但始终出现以下错误:
Error
Exception: DNS error: https://www.mots.go.th/images/v2022_1741001884711RmViLTIwMjVQLnhsc3g=.xlsx
(未使用encodeURIComponent时)
或
Error
Exception: DNS error: https://www.mots.go.th/images/v2022_1741001884711RmViLTIwMjVQLnhsc3g%3D.xlsx
(使用encodeURIComponent时)
不清楚为何该特定URL会出现此问题,正常情况下不会有这类问题。以下是用于提取blob的代码:
function apiFetch() { // URL part var encodeComponent = "v2022_1741001884711RmViLTIwMjVQLnhsc3g=.xlsx" var baseurl = "https://www.mots.go.th/images/" var url = baseurl + encodeURIComponent(encodeComponent) // Fetch contents from API endpoint. const apiResponse = UrlFetchApp.fetch(url).getBlob(); }
不确定该URL如何获取Excel文件,也不确定是否存在自动重定向到UrlFetchApp不兼容地址(如私有服务器)的情况,导致GAS出现DNS错误但浏览器无此问题,社区有人提出此推测但无法验证。
无论如何,尝试以下处理重定向的方法,仍出现相同DNS错误:
const apiResponse = UrlFetchApp.fetch(url, {'followRedirects': false, 'muteHttpExceptions': false});
尝试获取重定向URL的操作也失败,仍出现相同DNS错误:
var followedPost = UrlFetchApp.fetch(url, {'followRedirects': false, 'muteHttpExceptions': false}); Logger.log(followedPost.getHeaders()['Location']);
甚至尝试了专门获取重定向地址的脚本,仍出现相同DNS错误。
内容的提问来源于stack exchange,提问作者Joe Bah

