【问题标题】:Struggling to query specific element among others with the same class name using .querySelector努力使用 .querySelector 查询具有相同类名的特定元素
【发布时间】:2019-03-27 10:02:15
【问题描述】:

所以我正在尝试使用 Puppeteer 抓取网站。我要获取的所有数据都在多个表中。具体来说,我正在尝试从单个表中获取数据。我能够使用非常冗长的.querySelector(table.myclass ~ table.myclass) 获取特定表,所以现在我的问题是,我的代码正在获取每个表的第一项(从正确的表开始,即第二个表),但我不能找不到方法让它只抓取第二个表中的所有数据。

const puppeteer = require('puppeteer');
const myUrl = "https://coolurl.com";

(async () => {
  const browser = await puppeteer.launch({
    headless: true
  });
  const page = (await browser.pages())[0];
  await page.setViewport({
    width: 1920,
    height: 926
  });
  await page.goto(myUrl);

  let gameData = await page.evaluate(() => {
    let games = [];
    let gamesElms = document.querySelectorAll('table.myclass ~ table.myclass');
    gamesElms.forEach((gameelement) => {
      let gameJson = {};
      try {
        gameJson.name = gameelement.querySelector('.myclass2').textContent;
      } catch (exception) {
        console.warn(exception);
      }
      games.push(gameJson);
    });
    return games;
  })
  console.log(gameData);
  browser.close();
})();

【问题讨论】:

  • document.querySelectorAll('table.myclass ~ table.myclass') 抓取除第一个表之外的所有表。 .querySelector(table.myclass ~ table.myclass) 只返回第一个匹配的元素(也就是第二个表)
  • @marzelin 谢谢!不敢相信我没有发现。
  • @marzelin,应该作为答案发布吗? :D

标签: javascript node.js web-crawler google-chrome-devtools puppeteer


【解决方案1】:

您可以使用以下任一方法选择第二个表:

let gamesElms = document.querySelectorAll('table.myclass')[1];
let gamesElms = document.querySelector('table.myclass:nth-child(2)');

此外,您可以使用下面的示例将表中的所有数据推送到数组中:

let games = Array.from(document.querySelectorAll('table.myclass:nth-child(2) tr'), e => {
  return Array.from(e.querySelectorAll('th, td'), e => e.textContent);
});

// console.log(games[rowNum][cellNum]); <-- textContent

【讨论】:

  • 这很好用,谢谢!我很好奇您是否可以进一步澄清您的示例中发生了什么?我正计划走一个完全不同的方向,速记语法有点让我吃惊。如果没有,不用担心。
  • @RyanMcguinn 当然!在示例中,对于第二个表中的每个表行,我将 mapped 数组 textContent 从每个行单元格到较大的结果数组。结果是一个二维数组,它先按行索引,然后按单元格编号(以0 开头)。
猜你喜欢
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多