Search code examples
google-apps-scriptgoogle-sheetsweb-scrapinggoogle-sheets-formulaurlfetch

Google docs ImportXML called from script


I am using ImportXML in a google docs sheet to aqcuire data from the sistrix api. It works fine but I encountered the limitation of 50 ImportXML commands in one sheet. So I used a script that writes the ImportXML command to a cell (temporary) formula and takes back the resulting value of the cell and copies it to the destination cell. So you can do as much ImportXML queries as you need, as they only appear in one temporary cell in the sheet. The problem here is, that the ImportXML query SOMETIMES takes very long or returns with N/A.

Is it possible that my script sometimes doesnt wait for the ImportXML query to return and so the result is corrupted? I am currently doing it in this way:

function GetFormulaData(formula, sheet, row, col)
{

// write the formula (ImportXML(...)) to the specified cell
sheet.getRange(row, col).setFormula(formula);

// return the value of this cell resulting from the formula
return sheet.getRange(row, col).getValue();  
}

So this can obviously only work if the formula (the ImportXML query) is done and has written the return value into the cell, so I can read afterwards.
Does anybody have experience or alternatives with calling ImportXML from a script?


Solution

  • I have solved this now in a different way. It is more common to use UrlFetchapp() within google doc scripts than ImportXML. But you have to gain the xml data yourself from the http response.

    I do it in this way now:

    var response = UrlFetchApp.fetch(apiString).getContentText();
    var xmlContent = Xml.parse(response, true);
    var answer = xmlContent.response.answer; 
    
    // get what you need from the XML answer
    if (answer != null)
    {
        var element = answer.getElement('foo');
        if (element != null)
        {
            var attrib = element.getAttribute('bar');    
            if (attrib != null)
                value = attrib.getValue();  // the value you want
        }
    }