【问题标题】:How to pull HTML table data with Cheerio in Google Apps Script?如何在 Google Apps 脚本中使用 Cheerio 提取 HTML 表格数据?
【发布时间】:2021-11-19 19:43:45
【问题描述】:

受到来自this answer 的 Cheerio 如此便利的启发,我尝试在以下代码中使用它。代码能够通过调用 class="snapshot-td2" 来提取任何表数据,但我只想获取第一个表中的数据。我怎样才能做到这一点? URL 有两个表,分别为 class="snapshot-td2"。它以字符串形式检索它们。我怎样才能把它们放在数组中?感谢您的帮助!

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

  // The next line returned the tableValue from two tables of having class="snapshot-td2".
  // What should be modified to get the tableValue only from the first table? 
  // The next line returned the tableValue in string.  What should be modified to get them in array?
  var tableValue = page('.snapshot-td2').text();
  console.log(tableValue);
}

【问题讨论】:

    标签: google-apps-script web-scraping html-table cheerio


    【解决方案1】:

    无论如何,我都不是 jQuery 方面的专家,所以我的解决方案可能非常愚蠢。但它有效:

    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);
    }
    

    如果你想要一个数组(不是表格),data 就是数组。每个偶数元素,其中 [0,2,4...] 是一个名称,每个奇数元素 [1,3,5...] 是一个值。

    您可以很容易地将其转换为 2 列 [[name, value], [name, value]...]:

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

    或者变成一个对象{name:value, name:value, name:value...}:

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

    【讨论】:

    • 多么好的解释!非常感谢!
    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多