如何在Google Apps Script中调用DOMParser?解析网页报错求助
解决Google Apps Script中DOMParser未定义的问题
错误原因
Google Apps Script的服务器端运行环境不支持浏览器专属的DOMParser API,直接在服务器端函数中调用new DOMParser()会触发ReferenceError。
解决方案1:使用XmlService解析HTML
XmlService是Google Apps Script内置的XML解析工具,可处理符合XML规范的HTML(部分不规范HTML需简单预处理)。修改后的代码如下:
function countTablesInHTMLDoc(url) { var htmlString = UrlFetchApp.fetch(url).getContentText(); // 预处理HTML,适配XmlService的解析规则 var cleanedHtml = htmlString.replace(/<br>/g, '<br/>') .replace(/<hr>/g, '<hr/>') .replace(/(<[^>]+)\/>/g, '$1>'); try { var document = XmlService.parse(cleanedHtml); var root = document.getRootElement(); // 递归统计所有table标签 var tableCount = countElements(root, 'table'); return tableCount; } catch (e) { Logger.log('解析HTML出错:' + e.toString()); return -1; } } function countElements(element, tagName) { var count = element.getName() == tagName ? 1 : 0; var children = element.getChildren(); for (var i = 0; i < children.length; i++) { count += countElements(children[i], tagName); } return count; } function exampleUsage() { var url = "https://stihi.ru/readers.html?vlassoff&start=0"; var tableCount = countTablesInHTMLDoc(url); Logger.log("Количество таблиц в документе по ссылке " + url + ": " + tableCount); }
解决方案2:通过HtmlService在客户端处理
借助HtmlService创建临时网页,在浏览器环境(支持DOMParser)中完成解析,再将结果返回服务器端:
- 创建HTML文件:在脚本编辑器中选择「文件」→「新建」→「HTML文件」,命名为
ParserPage,填入以下内容:
<!DOCTYPE html> <html> <body> <script> function parseHtmlAndCountTables(htmlString) { var parser = new DOMParser(); var doc = parser.parseFromString(htmlString, "text/html"); return doc.getElementsByTagName("table").length; } google.script.run.withSuccessHandler(function(count) { google.script.run.logTableCount(count); window.close(); }).withFailureHandler(function(error) { google.script.run.logError(error); window.close(); }).getHtmlToParse(); </script> </body> </html>
- 修改服务器端脚本:
function countTablesInHTMLDoc(url) { var htmlString = UrlFetchApp.fetch(url).getContentText(); PropertiesService.getScriptProperties().setProperty('htmlToParse', htmlString); // 打开临时弹窗执行解析 var html = HtmlService.createHtmlOutputFromFile('ParserPage').setWidth(100).setHeight(100); SpreadsheetApp.getUi().showModalDialog(html, '解析中...'); } function getHtmlToParse() { return PropertiesService.getScriptProperties().getProperty('htmlToParse'); } function logTableCount(count) { Logger.log("Количество таблиц в документе: " + count); PropertiesService.getScriptProperties().deleteProperty('htmlToParse'); } function logError(error) { Logger.log("解析出错: " + error); PropertiesService.getScriptProperties().deleteProperty('htmlToParse'); } function exampleUsage() { var url = "https://stihi.ru/readers.html?vlassoff&start=0"; countTablesInHTMLDoc(url); }
注意:方案2需在有UI的环境中运行(如绑定Google表格的脚本,通过自定义菜单触发),直接在脚本编辑器运行可能因无UI环境报错。
内容的提问来源于stack exchange,提问作者Тульский Самовар
相关产品推荐
相关产品推荐

