Click button if present, else click a different button
See original GitHub issueSteps to reproduce
Tell us about your environment:
- Puppeteer version: 1.4.0
- Platform / OS version: MacOS 10.12.6
- URLs (if applicable):
- Node.js version: 8.9.1
What steps will reproduce the problem?
Please include code that reproduces the issue.
I am trying to set up an if/else
statement in puppeteer to click on a button if it is present, else click on other button first, then click on the button I am trying to get to. I am doing something like this:
if ((await page.$('#buttonToClick')) !== null) {
await page.click('#buttonToClick');
} else {
await page.waitForSelector('#otherButton');
await page.click('#otherButton');
await page.waitForSelector('#buttonToClick');
await page.click('#buttonToClick');
}
For some reason I keep falling into the else
block even when I go to my Chrome console and do a document.querySelector('#buttonToClick') !==null
on the desired page and it is showing as true
I also tried doing:
await page.waitForNavigation({ waitUntil: 'networkidle0' });
if (await page.$('#buttonToClick') !== null) {
await page.click('#buttonToClick');
} else {
await page.waitForSelector('#otherButton');
await page.click('#otherButton');
await page.waitForSelector('#buttonToClick');
await page.click('#buttonToClick');
}
But that didn’t work either. I also swapped out the above line: await page.waitForNavigation({ waitUntil: 'networkidle0' });
for await page.waitForNavigation({ waitUntil: 'domcontentloaded' });
and also tried await page.waitForNavigation({ waitUntil: 'networkidle2' });
and none of those seemed to work.
The ONLY way I can get the expected result I am looking for is if I write the following code:
await page.waitFor(1000);
if ((await page.$('#buttonToClick')) !== null) {
await page.click('#buttonToClick');
} else {
await page.waitForSelector('#otherButton');
await page.click('#otherButton');
await page.waitForSelector('#buttonToClick');
await page.click('#buttonToClick');
}
But I don’t necessarily like the idea of having to do a page.waitFor()
for a fixed number of seconds…any ideas what could be going on? Any help is appreciated, thanks so much in advance!
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:7 (3 by maintainers)
Top GitHub Comments
A better idea is
Promise.race
to make it faster, likeThe main difference is that instead of just having a timeout, you have a ‘waitForSelector’, with a timeout. In case this timeout passes, promise will be rejected (with a timeout error). You can catch this error and have your fallback - click another button. Does it makes sense for your case?