我有两个这样的文本跨度。
<span class="date">today</span>
<span class="date">tomorrow</span>
我想获取这些文本并在终端上console.log()
。我该怎么办?
谢谢。
答案 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);
}
})();