Home > Back-end >  Stop the loop after the n-th element - puppeteer
Stop the loop after the n-th element - puppeteer

Time:07-22

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!

CodePudding user response:

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"});

}

  • Related