Home > Back-end >  How to pull HTML table data with Cheerio in Google Apps Script?
How to pull HTML table data with Cheerio in Google Apps Script?

Time:09-28

Inspired by such a convenience of Cheerio from enter image description here

CodePudding user response:

I'm not an expert in jQuery by any means so probably my solutions is quite stupid. But it works:

function test2() {
  const url = 'https://finviz.com/quote.ashx?t=AFRM';
  const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
  const $ = Cheerio.load(res);

  var data = $('table.snapshot-table2').find('td').toArray().map(x => $(x).text());

  var table = []
  for (var i=0; i<data.length; i =12) {
    row = [];
    for (var j=0; j<12; j  ) row.push(data[i j]);
    table.push(row);
  }

  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,table.length,table[0].length);
  range.setValues(table);
}

enter image description here

If you want an array (not a table) the data is the array. Every even element of which [0,2,4...] is a name, and every odd element [1,3,5...] is a value.

You can convert it into 2 columns [[name, value], [name, value]...] pretty easy:

var table = [];
for (var i=0; i<data.length; i =2) table.push(data[i], data[i 1]);

Or into an object {name:value, name:value, name:value...}:

var obj = {};
for (var i=0; i<data.length; i =2) obj[data[i]] = data[i 1]);
  • Related