简体   繁体   中英

PUPPETER - Random timeout inside loop not working

So, i have code like this (only this part is not working properly)

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    // slowMo: 250 // slow down by 250ms
  });
  const page = await browser.newPage();
//some code

// CODE ABOVE WORKS, here is what is not working inside of it:

await page.evaluate(() => {
    function delay(timeout) {
      return new Promise((resolve) => {
        setTimeout(resolve, timeout);
      });
    }
    function randomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    const farms = document.querySelectorAll(".startButton");
    for (let i = 0; i < 3; i++) {
      for (const farm of farms) {
        farm.click();
      }
      delay(randomInteger(820000, 920000));
    }
  });
})();

What i want is, to select all buttons with this class, click them, and then wait some time, and click them again, but it looks like delay function isnt working here - or is not executed (but in other part of the code, it works so idk where is a problem and i ask for Your help: :D

#EDIT

The code (with added async and await as @Sheun Aluko said) is good, it wasnt working due to website security system, so i needed to apply new fix that refresh/go to the same page, and change the loop order, maybe its not as efficient, but it works 100%. here is example:

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    // slowMo: 250 // slow down by 250ms
  });

//SOME CODE THAT WORKS
//OUR PART BELOW

  for (let i = 0; i < 150; i++) {
    await page.goto("SOME_URL", {
      waitUntil: "networkidle2",
    });
    await page.evaluate(async (page) => {
      function delay(timeout) {
        return new Promise((resolve) => {
          setTimeout(resolve, timeout);
        });
      }
      function randomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

      const farms = document.querySelectorAll('SOME_SELECTOR');

      for (const farm of farms) {
        farm.click();
      }
      await delay(randomInteger(840000, 960000));
    });
  }
})

I can see that the delay function returns a promise. In the last line, I believe you should instead be calling await delay(randomInteger(820000, 920000)) so that the loop actually waits before the next iteration.

In response to the error you mentioned, this is happening because the function you are passing to page.evaluate is not marked as async. Im not totally familiar with Puppeteer, but can you try marking the provided function as async.. ie:

await page.evaluate( async () => { 
   ....
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM