Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer - counting elements by class name

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 scrolling 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.

like image 722
user1584421 Avatar asked Jun 01 '18 14:06

user1584421


People also ask

How do you find the element by name in puppeteer?

puppeteer find element by text You have to form XPath based on the text so that you can find the element. Once you form the XPath then you can use the $x method to find the element.

How do you find the value of an element in a puppeteer?

page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.


1 Answers

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()
like image 53
Simone Sanfratello Avatar answered Oct 16 '22 06:10

Simone Sanfratello