up:等待N秒钟,然后继续下一行 [英] puppeteer: wait N seconds before continuing to the next line
问题描述
在 puppeteer 中,我想等待一段确定的时间,然后再转到下一行代码。
In puppeteer I would like to wait a defined time before going to the next line of code.
我尝试放置一个 setTimeout
在评估函数中,但似乎只是被忽略
I've tried to put a setTimeout
in an evaluate function but it seems to be simply ignored
console.log('before waiting');
await page.evaluate(async() => {
setTimeout(function(){
console.log('waiting');
}, 4000)
});
console.log('after waiting');
此代码无需等待,只需在等待之前写 和在等待之后 / em>
This code don't wait and just write before waiting and after waiting
您知道怎么做吗?
推荐答案
您可以使用一个小的承诺函数,
You can use a little promise function,
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time)
});
}
然后,在需要延迟的时候调用它。
Then, call it whenever you want a delay.
console.log('before waiting');
await delay(4000);
console.log('after waiting');
如果必须使用puppeteer,请使用内置的waitFor函数。
If you must use puppeteer use the builtin waitFor function.
await page.waitFor(4000)
如果仍然要使用page.evaluate,请在4秒钟后解决。您没有解决任何问题。
If you still want to use page.evaluate, resolve it after 4 seconds. You are not resolving anything.
await page.evaluate(async() => {
await new Promise(function(resolve) {
setTimeout(resolve, 1000)
});
});
但是我想您可以简单地使用前两个示例。
But I guess you can simply use the first two examples.
这篇关于up:等待N秒钟,然后继续下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!