Puppeteer - 按类名计数元素 [英] Puppeteer - counting elements by class name

查看:472
本文介绍了Puppeteer - 按类名计数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将有关具有特定类名的所有元素的信息添加到数组中。

I am trying to get info about all the elements with a particular class name into an array.

问题是这是一个动态生成的HTML页面,并且只要我向下滚动,该类名的新元素就会出现。

The problem is this is a dynamically generated HTML page, and as long as i scroll down, new elements of that class name appear.

幸运的是,我事先知道有多少这些元素存在。

Fortunately, i know beforehand how many of these elements exist.

所以我的假设解决方案是检查具有该特定类名的元素数量,只要该数字小于我所知道的数字,就继续骂人。

So my hypothetical solution is to check the number of elements with that particular class name, and as long as that number is less than the one i know, keep scolling down.

问题是我不知道如何计算puppeteer中特定类名的元素,API也不是很有用。

The problem is i don't know exactly how to count elements of a particular class name inside puppeteer and the API was not very useful either.

推荐答案

我认为这就是你要找的东西

I think this is what you are looking for

const puppeteer = require('puppeteer')

async function count () {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'})
  await page.evaluate(_ => {
    window.scrollBy(0, window.innerHeight)
  })

  console.log('how many?', (await page.$$('td.title')).length)

  await browser.close()
}

count()

这篇关于Puppeteer - 按类名计数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆