javascript - 如何使用Puppeteer统计网页上特定文本的出现次数?

标签 javascript node.js web-scraping puppeteer text-search

我正在使用 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/

相关文章:

node.js - Node 从 axios post 接收 post json

javascript - 如何将批量通知 API 与 Cloud Functions for Firebase 结合使用?

Python添加到MySQL数据库

c# - 在 javascript 中使用 c# 类对象

javascript - 他们如何在鼠标悬停时隐藏 URL?

javascript - 是否可以隐藏或操纵 jqGrid "sort"图标?

node.js - 在 OpenShift 上运行 Gulp 构建

python - 我有 12000 个已知 URL,用 Python 抓取它们的最快方法是什么?

python - 使用 Mechanize : Can't retrieve form? 进行 ASPX 抓取

java - 使用 webdriver 检测远程计算机上的操作系统的包装类?