javascript - await page.waitFor inside page.evaluate in puppeteer? - Stack Overflow

I was wondering if you could do something likepage.evaluate((page) => {Code to execute beforeawait

I was wondering if you could do something like

 page.evaluate((page) => {
     //Code to execute before
     await page.waitFor(1000);
     //Code to execute after the 1000ms time delay
 }, page);

If this isn't possible, how would one introduce such a time delay?

Oh, final note, doing something like this isn't a viable option for time delay in my project:

 function delay(time) {
     let curtime = new Date().getTime();
     time += curtime;
     while(curtime < time) {
         curtime = new Date().getTime();
     } 
 }

CPU matters on this, and I don't wanna have some while loop executing thousands of times for a simple delay

I was wondering if you could do something like

 page.evaluate((page) => {
     //Code to execute before
     await page.waitFor(1000);
     //Code to execute after the 1000ms time delay
 }, page);

If this isn't possible, how would one introduce such a time delay?

Oh, final note, doing something like this isn't a viable option for time delay in my project:

 function delay(time) {
     let curtime = new Date().getTime();
     time += curtime;
     while(curtime < time) {
         curtime = new Date().getTime();
     } 
 }

CPU matters on this, and I don't wanna have some while loop executing thousands of times for a simple delay

Share Improve this question asked Dec 14, 2019 at 4:37 John SmithJohn Smith 1174 silver badges15 bronze badges 2
  • you would need to make your arrow function async for the first code block to work (ie: async (page) => {) – Nick Parsons Commented Dec 14, 2019 at 4:39
  • This is the error I get from doing that: UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON Are you passing a nested JSHandle? – John Smith Commented Dec 14, 2019 at 5:02
Add a ment  | 

1 Answer 1

Reset to default 8
  1. await can only be used in async functions.
  2. The function in evaluate will be evaluated in the page context so either:

Use setTimeout():

page.evaluate(() => {
     //Code to execute before
     setTimeout(function() {
       //Code to execute after the 1000ms time delay
     }, 1000);    
 });

Or write your async delay function similar to page.waitFor in puppeteer.

function waitFor(delay) {
    return new Promise(resolve => setTimeout(resolve, delay));
}

Then you will have:

page.evaluate(async() => {
     //Define your waitFor function
     //Code to execute before
     await waitFor(1000);
     //Code to execute after the 1000ms time delay
 });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744317771a4568265.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信