Home > Back-end >  How to count div items in node js
How to count div items in node js

Time:08-13

i am new to node js , I would like to count the total div items on the webpage with node js , i tried with document get element by id but it invoke reference error that document cannot be used with node , is there any npm module which can be use to count div items on page

here is my sample code


const puppeteer = require('puppeteer');
(async() => {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: false,
        args: ['--start-maximized']
    });
    const page = await browser.newPage();
  
      await page.goto('http://www.uitu.edu.pk/');
  
})();


Inside inspect element I have find the div with class name row , inside that div there following six items(sub divs)

#cards_landscape_wrap-2 > div > div.row > div:nth-child(1)
#cards_landscape_wrap-2 > div > div.row > div:nth-child(2)
#cards_landscape_wrap-2 > div > div.row > div:nth-child(3)
#cards_landscape_wrap-2 > div > div.row > div:nth-child(4)
#cards_landscape_wrap-2 > div > div.row > div:nth-child(5)
#cards_landscape_wrap-2 > div > div.row > div:nth-child(6)

I want to count these divs , so when my script runs I can count these divs

CodePudding user response:

Actually, there are seven divs:
enter image description here

To count how many just select all divs with querySelectorAll and get its count with length property.

document.querySelectorAll('#cards_landscape_wrap-2 > div > div.row > div').length; // 7 

Try this code:

const puppeteer = require("puppeteer");
(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: false,
    args: ["--start-maximized"],
  });
  const page = await browser.newPage();
  await page.waitForSelector("#cards_landscape_wrap-2");
  const len = await page.evaluate(() => {
    return document.querySelectorAll(
      "#cards_landscape_wrap-2 > div > div.row > div"
    ).length;
  });
  console.log(len);
  browser.close();
})();
  • Related