Puppeteer :超时或睡眠或在 Page.Evaluate() 内等待

Puppeteer : Timeout or sleep or wait inside Page.Evaluate()

我需要一种方法来在单击 page.evaluate 函数

中的元素之间添加一些延迟

以下是我尝试过的方法,但它不起作用

const result = await page.evaluate(async () => {
        let variants = document.querySelectorAll(".item-sku-image a");


        variants.forEach(async variant => {   
           await new Promise(function(resolve) { 
           setTimeout(resolve, 1000)
           });         
            await variant.click()
        });
        return data
    });

更新:

下面的 for 循环对一个元素工作正常 当我尝试在其中使用另一个 for 循环时 - 它变得疯狂

const variants = [...document.querySelectorAll(".item-sku-image a")]; // Turn nodelist into an array
const sizes = [...document.querySelectorAll(".item-sku-size a")]; // Turn nodelist into an array

for (let variant of variants){
  // wait one second
  await new Promise(function(resolve) {setTimeout(resolve, 1000)});
  await variant.click()
  for (let size of sizes){
   // wait one second
   await new Promise(function(resolve) {setTimeout(resolve, 1000)});
   await size.click()
 }
}

.forEach 将无法按照您的承诺或 async...await 的方式工作。

改用for..of

const variants = [...document.querySelectorAll(".item-sku-image a")]; // Turn nodelist into an array
for (let variant of variants){
  // wait one second
  await new Promise(function(resolve) {setTimeout(resolve, 1000)});
  await variant.click()
}

易于阅读、理解和实施。

参考资料如下: