Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
Stop the loop after the n-th element - puppeteer

How can I stop the loop after the fifth link?

This is my code

  await page.goto('https://old.reddit.com',{"waitUntil" : "networkidle0"});
  const a_elems = await page.$$('.thumbnail');

  for (var i=0; i<a_elems.length; i++) {                  
     const elem = a_elems[i];
     const href = await page.evaluate(e => e.href, elem); 
     const newPage = await browser.newPage();
     await newPage.goto(href,{"waitUntil" : "networkidle0"});
   }

I tried nth-child but it doesn't work. Do you have any ideas? Thank you!

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

by simply add the condition in your for loop

 for (var i=0; i<a_elems.length && i<5; i++) {                  
 const elem = a_elems[i];
 const href = await page.evaluate(e => e.href, elem); 
 const newPage = await browser.newPage();
 await newPage.goto(href,{"waitUntil" : "networkidle0"});

}

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!