【问题标题】:Puppeter: Web Scraping a Table (Array of Strings?)Puppeteer:Web 抓取表格(字符串数组?)
【发布时间】:2020-03-19 23:20:49
【问题描述】:

我正在尝试从表 listed on this website. 中抓取数据我能够抓取 updateDate,但我遇到了列和行的问题。

我要抓取的表嵌套在td 中,ID 为col2

我的问题:

我似乎无法弄清楚如何正确查询行,因此我可以获得所有数字数据(每行一个字符串数组);

表格(来自 Inspector):

我的代码:

// Find Table Rows
console.log('Searching for COVID-19 Data from Orange County');

// Table Rows
let tableRows = await page.$$('#col2 > div > table > tbody > tr');
// console.log(tableRows);

// Check For Table Rows
if (tableRows.length > 0) {
  console.log('Table Rows found');

  // Update Date (Length: 10)
  if (await tableRows[2].$$('tr > td')) {
    // Assign Element (First Row)
    let updateField = String(await tableRows[2].$eval('tr > td', td => td.innerText.trim()));

    // Check If Matches
    if (updateField.match(/(as of [0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9])/)) {
      const updateDate = updateField.slice(51, updateField.length - 1).trim();
      console.log(`Update Date: ${updateDate}`);
    }
    else {
      throw error('Error: Update Date doesn\'t match format');
    } 
  }

  // Cases
  if (await tableRows[5].$$('tr > td')) {
    // Assign Element (First Row)
    let totalCasesField = String(await tableRows[5].$eval('tr > td', td => td.innerText.trim()));
    console.log(totalCasesField);
  }

【问题讨论】:

    标签: javascript node.js web-scraping puppeteer


    【解决方案1】:

    这样的?

    const puppeteer = require('puppeteer');
    
    (async function main() {
      try {
        const browser = await puppeteer.launch();
        const [page] = await browser.pages();
    
        await page.goto('https://www.ochealthinfo.com/phs/about/epidasmt/epi/dip/prevention/novel_coronavirus');
    
        const data = await page.evaluate(() => {
          const table = document.querySelector('#col2 > div > table + table');
          const rowsWithNumbers = [...table.rows].slice(3, 9);
          const numbers = rowsWithNumbers.map(
            row => [...row.cells].slice(1).map(cell => cell.innerText)
          );
          return numbers;
        });
    
        console.log(data);
    
        await browser.close();
      } catch (err) {
        console.error(err);
      }
    })();
    
    

    结果:

    [
      ['42', '26', '16', '0',  '21', '13', '8'],
      ['22', '13', '9', '0',  '10', '8', '4'],
      ['7', '6', '1', '0', '5', '2', '0'],
      ['12', '7', '5', '0',  '5', '3', '4'],
      ['1', '0', '1', '0', '1', '0', '0'],
      ['0', '0', '0', '0', '0', '0', '0']
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多