Lim*_*fro 1 javascript node.js puppeteer
我需要一种在 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
});
Run Code Online (Sandbox Code Playgroud)
更新:
当我尝试在其中使用另一个 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()
}
}
Run Code Online (Sandbox Code Playgroud)
.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()
}
Run Code Online (Sandbox Code Playgroud)
它易于阅读、理解和实施。
以下是一些参考: