在谷歌应用程序脚本中解析 html 的最佳方法是什么 [英] What is the best way to parse html in google apps script

查看:23
本文介绍了在谷歌应用程序脚本中解析 html 的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var page = UrlFetchApp.fetch(contestURL);
var doc = XmlService.parse(page);

上面的代码在使用时会出现解析错误,但是如果我将 XmlService 类替换为已弃用的 Xml 类,并设置了 lenient 标志,它会正确解析 html.

The above code gives a parse error when used, however if I replace the XmlService class with the deprecated Xml class, with the lenient flag set, it parses the html properly.

var page = UrlFetchApp.fetch(contestURL);
var doc = Xml.parse(page, true);

该问题主要是由于 html 的 javascript 部分中没有 CDATA 而导致解析器抱怨以下错误.

The problem is mostly caused because of no CDATA in the javascript part of the html and the parser complains with the following error.

The entity name must immediately follow the '&' in the entity reference.

即使我使用正则表达式删除所有 <script>(.*?)</script>,它仍然会抱怨,因为 <br> 标签没有关闭.有没有一种干净的方法可以将 html 解析为 DOM 树.

Even if I remove all the <script>(.*?)</script> using regex, it still complains because the <br> tags aren't closed. Is there a clean way of parsing html into a DOM tree.

推荐答案

我遇到了完全相同的问题.我能够通过首先使用已弃用的 Xml.parse 来规避它,因为它仍然有效,然后选择主体 XmlElement,然后将其 Xml 字符串传入新的 XmlService.parse方法:

I ran into this exact same problem. I was able to circumvent it by first using the deprecated Xml.parse, since it still works, then selecting the body XmlElement, then passing in its Xml String into the new XmlService.parse method:

var page = UrlFetchApp.fetch(contestURL);
var doc = Xml.parse(page, true);
var bodyHtml = doc.html.body.toXmlString();
doc = XmlService.parse(bodyHtml);
var root = doc.getRootElement();

注意:如果旧的 Xml.parse 从 Google Scripts 中完全删除,则此解决方案可能不起作用.

Note: This solution may not work if the old Xml.parse is completely removed from Google Scripts.

这篇关于在谷歌应用程序脚本中解析 html 的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆