Puppeteer - counting elements by class name

我是研究僧i 提交于 2019-12-10 09:49:14

问题


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

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.

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.


回答1:


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()


来源:https://stackoverflow.com/questions/50645795/puppeteer-counting-elements-by-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!