我的代码有效:
function getElementsByClassName(element, classToFind) {
var data = [];
var descendants = element.getDescendants();
descendants.push(element);
for(i in descendants) {
var elt = descendants[i].asElement();
if(elt != null) {
var classes = elt.getAttribute('class');
if(classes != null) {
classes = classes.getValue();
if(classes == classToFind) data.push(elt);
else {
classes = classes.split(' ');
for(j in classes) {
if(classes[j] == classToFind) {
data.push(elt);
break;
}
}
}
}
}
}
return data;
}
function getElementsByTagName(element, tagName) {
var data = [];
var descendants = element.getDescendants();
for(i in descendants) {
var elt = descendants[i].asElement();
if( elt !=null && elt.getName()== tagName) data.push(elt);
}
return data;
}
function test() {
var options = {};
options.headers = {"Authorization": "Basic " + Utilities.base64Encode("user" + ":" + "password")};
var html = UrlFetchApp.fetch("http://url", options).getContentText();
var doc = XmlService.parse(html);
var html = doc.getRootElement();
var table = getElementsByClassName(html, 'test')[0];
var tds = getElementsByTagName(table, 'td');
var row = [];
for (var c=0,clength=tds.length; c<clength; c++) {
row.push(tds[c].getText());
}
return row;
}
但是如果我将这个循环添加到测试函数中,我得到:
&#34;超过最长执行时间&#34;
错误,但不起作用。
var rows = [];
var trs = getElementsByTagName(table, 'tr');
for (var r=0,rlength=trs.length; r<rlength; r++) {
var tds = getElementsByTagName(table, 'td');
var row = [];
for (var c=0,clength=tds.length; c<clength; c++) {
row.push(tds[c].getText());
}
rows.push(row);
}
return rows;
有效的代码将所有html表格单元格放在Google表格的一列中,但代码的第二部分也应该带来html表格列,但由于某些原因它不起作用。