Warm tip: This article is reproduced from serverfault.com, please click

How to wait for a button to be enabled and click with puppeteer?

发布于 2020-01-23 15:58:00

I have a form with two fields username and password. Once the username is entered the next button is enabled, once I click on it, it shows a password field and once that's entered, it enables the next button again. How do I wait for the button to be enabled in between form updates?

I tried the below approaches, one is commented and the other is not. Both don't work for me.


(async () => {
    const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('http://localhost:9000/start#!');

await page.type('#login-form-un-field', 'xxxx')
// await page.waitForTarget('#default-next-btn:not([disabled])')
await page.$eval('#default-next-btn:not([disabled])', elem => elem.click());
// const btnNext = await page.$('#default-next-btn');
// btnNext.click();
await page.type('login-form-passcode', '1234');
await page.click('#default-next-btn');
await browser.close();
})();```

Thanks for the help in advance.

Edit: the button is always present on the page. It is just disabled while form entries are being validated.

Questioner
DJR
Viewed
1
3,693 2020-11-11 00:43:07

you can use await page.waitForSelector(selector) => docs

your code became:

(async () => {

    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.goto('http://localhost:9000/start#!');

    await page.type('#login-form-un-field', 'xxxx')

    await page.waitForSelector('YOUR_SELECTOR_1')
    await page.click('YOUR_SELECTOR_1')

    await page.type('login-form-passcode', '1234');

    await page.waitForSelector('YOUR_SELECTOR_2')
    await page.click('YOUR_SELECTOR_2')

    await browser.close();
})();