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?
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);
}
}
})
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With