如何在操纵up中获取文本元素

时间:2020-10-04 16:26:52

标签: puppeteer

我有两个这样的文本跨度。

<span class="date">today</span>
<span class="date">tomorrow</span>

我想获取这些文本并在终端上console.log()。我该怎么办?

谢谢。

1 个答案:

答案 0 :(得分:0)

const puppeteer = require('puppeteer');

const html = `
  <!doctype html>
  <html>
    <head><meta charset='UTF-8'><title>Test</title></head>
    <body>
      <span class="date">today</span>
      <span class="date">tomorrow</span>
    </body>
  </html>`;

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

    await page.goto(`data:text/html,${html}`);

    const texts = await page.evaluate(() => Array.from(
      document.querySelectorAll('span.date'),
      span => span.innerText
    ));

    console.log(texts); // [ 'today', 'tomorrow' ]

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();