Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer - Handlin page.waitForSelector() fails

If page.waitForSelector() fails, it throws an error. Since this is run inside an async function if leads straight to the catch portion of the code.

Is there a chance that if page.waitForSelector() fails, code is executed one line below?

Like this (pseudocode):

if ( (await page.waitForSelector('.test') == null) { //do X}

From the API:

If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.

How do i manage that throw in the same block of code, as if the fucntion would succeed?

like image 657
user1584421 Avatar asked Jul 26 '18 14:07

user1584421


2 Answers

why don't you catch the error which page.waitForSelector is throwing and do your actions after that something like this -

(async() => {

     try {
        page.waitForSelector(selector);
     } catch(error) {
       // do as you wish with this error and then do your next actions

           try {
                page.goto('someUrl');
           } catch(error) {
               throw new Error(error);
           }
     }

})
like image 190
Ram Pasala Avatar answered Nov 15 '22 02:11

Ram Pasala


What I do to detect if the selector is present inside loops like that is:

if (await page.$('.test')) {
  break
}

Keep in mind that after that, you don't need to waitForSelector or any waitFor, because you already know that this selector is present, so just continue the program, as I did below:

(Just for demonstration purposes, don't use it like this... If the website has any "bot protection", it's gonna drop you off after the second reload, probably you want to add some timeout for this, to emulate the user timing for reloads: await new Promise(resolve => setTimeout(resolve, 5000)), before the reload)

while(true) {
    if (await page.$('.test')) {
      break
    }
    page.reload()
}

page.click('.test')
like image 2
Pedro Filho Avatar answered Nov 15 '22 04:11

Pedro Filho