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

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

问题描述

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

上面的代码在使用时给出了一个分析错误,但是如果我用废弃的Xml替换XmlService类类,设置宽松标志,它会正确解析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 code>完全从Google脚本中删除。

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

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

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