我正在使用 NodeJS 和 Puppeteer 库来加载网站,然后检查页面上是否显示特定文本。我想计算这个特定文本出现的次数。具体来说,我希望此搜索的工作方式与 Chrome 或 Firefox 中 Ctrl+F
功能的工作方式完全相同。
这是我到目前为止的代码:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// How do I count the occurrences of the specific text here?
await browser.close();
})();
有人可以帮我解决如何实现这一目标吗?任何帮助将不胜感激。
最佳答案
import puppeteer from 'puppeteer'
(async () => {
const textToFind = 'domain'
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://example.com')
const text = await page.evaluate(() => document.documentElement.innerText)
const n = [...text.matchAll(new RegExp(textToFind, 'gi'))].length
console.log(`${textToFind} appears ${n} times`)
await browser.close()
})()
关于javascript - 如何使用Puppeteer统计网页上特定文本的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76060208/