如何捕获 XMLService getAttribute 方法中的执行错误?

How to catch execution error in XMLService getAttribute method?

我在 Google 表格电子表格中使用此脚本来解析网页中的 table 并存储结果:

    var doc = XmlService.parse(result);
    var html = doc.getRootElement();
    var resulttable = getElementsByClassName(html, 'resulttable')[0];

    var descendants = html.getDescendants();
    descendants.push(html);  
    for(var i in descendants) {
      var elt = descendants[i].asElement();  <== it crashes
      if(elt != null) {
        var test = elt.getAttributes();
        var test_bis = elt.getAttribute('http-equiv');   <== it does not crashes: 'http-equiv' exists
        var classes = elt.getAttribute('class');   <== it crashes:'class' does not exists
      }
    }

如图所示,我在这段代码的标记行中有一些错误(简称为“服务器错误”)。我还放置了 try...catch 块,但它们没有发现错误:脚本突然终止。

我怎样才能捕获错误,以便让脚本继续执行,尽管其中有一些 XML 错误?

我的期望是当 asElementgetAttribute 方法失败时有未定义的元素。


解析 URL 我使用的是 this approach

  var url = "https://albopretorio.comune.gravina.ba.it/fo/?ente=GravinaInPuglia";
  var today = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy");

  var payload =
      {
        "tipoSubmit":"ricerca",
        "enti":"GravinaInPuglia",
        "uo":"",
        "tipoatto":"",
        "anno":"",
        "numda":"",
        "numa":"",
        "annoatto":"",
        "numatto":"",
        "datada":"",
        "dataa":"",
        "pubblicatoda":today,
        "pubblicatoa":"",
        "presenteal":"",
        "chiave":"",
        "provenienza":"",
      };
  
  var options =
      {
        "method"  : "POST",
        "payload" : payload,   
        "followRedirects" : true,
        "muteHttpExceptions": true
      };
var result = UrlFetchApp.fetch(url, options);

问题:

你不知道每个descendant是哪个ContentType,所以你不知道应该使用哪种方法来投射节点。

解决方案:

对于每个 descendant,使用方法 getType(). You can use the returned value (the ContentType) and a switch statement 检查相应的 ContentType 以使用一种或另一种方法。

代码片段:

for (var i in descendants) {
  var contentType = descendants[i].getType();
  var elt;
  switch (contentType.toString()) {
    case 'TEXT':
      elt = descendants[i].asText();
      break;
    case 'ELEMENT':
      elt = descedants[i].asElement();
      break;
    // Add other possible ContentTypes, if necessary

更新:getAttribute 问题:

为了避免脚本尝试检索不存在的属性,您可以检索该元素的属性名称数组,然后检查您的属性是否包含在该数组中:

var attributes = elt.getAttributes().map(attribute => attribute.getName());
if (attributes.includes('class')) {
  var classes = elt.getAttribute('class');
}

参考: