Search code examples
google-apps-scriptgoogle-sheetscheerio

how to map different classes within the same string using Google App Script and Cheerio?


Library used for Cheerio in Google App Script:

1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0



I want to collect everyone's text <td class="name large-link"> and of the <td class="name large-link"> existing in a string, I tried to map it as follows:

function TestOne() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Test One');
  var url = sheet.getRange('Test One!A1').getValue();
  
  const contentText = UrlFetchApp.fetch(url).getContentText();
  const $ = Cheerio.load(contentText);

  //Menu do Plantel
  $('#page_team_1_block_team_squad_7-table > tbody > tr > td')
  .each((index, element) => {
  sheet.getRange(index+2,2).setValue($(element.shirtnumber).text());
  sheet.getRange(index+2,3).setValue($(element.name.large-link).text());
  });
}

Note: I want to fetch the texts of all the class that exist in the table, but since it's so big, I've summarized it in two class just so I can understand what I need to do and add the rest later.

But I wasn't successful in returning and I couldn't find examples of how I can make this collection, I would like an indication so that I don't need to do several different loopings and merge them all into one.

The idea is to recreate this table in my spreadsheet:

enter image description here

Here the sitemap:

https://int.soccerway.com/teams/norway/fotballklub-bodoglimt/1595/squad/

enter image description here


Solution

  • It works for me, I got the example and made some modifications

       function myFunction() {
      const url = 'https://int.soccerway.com/teams/norway/fotballklub-bodoglimt/1595/squad/';
      const ss = SpreadsheetApp.getActive()
      const sh = ss.getSheetByName('Test One');
      const contentText = UrlFetchApp.fetch(url).getContentText();
      const $ = Cheerio.load(contentText);
    
      var header = Array();
    
      $("table tr th").each(function (i, v) {
        header[i] = $(this).text();
      })
    
      var data = Array();
    
      $("table tr").each(function (i, v) {
        data[i] = Array();
        $(this).children('td').each(function (ii, vv) {
          data[i][ii] = $(this).text();
        });
      })
    
    
    
      for (let i = 1; i < data.length - 6; i++) {
        console.log(data[i].length);
        console.log(data[i]);
        sh.getRange(i, 1, 1, data[i].length).setValues([data[i]]);
      }
    }
    

    enter image description here