Patrick Balada
Patrick Balada

Reputation: 1450

How to click a button by name or text with puppeteer?

I am new to puppeteer and stuck in trying to click a certain button on yahoo. I face the following situation:

enter image description here

enter image description here

I tried to select click on the button as follows:

const [button] = await page.$x("//button[contains(., 'OK')]");
if (button) {
   await button.click();
}

Unfortunately without success. How would I click on the OK button in general? And what would be a solution to check whether the button exists or not. Thank you very much for your help.

Upvotes: 12

Views: 36965

Answers (2)

Simon Thiel
Simon Thiel

Reputation: 3285

You can use the name attribute as a selector for name:

await page.waitForSelector('button[name="agree"]');
await page.click('button[name="agree"]');

Upvotes: 21

Adriano
Adriano

Reputation: 3934

From your browser, open the page where the button sits. Right click on the page and select "Inspect".

Then, from the DOM code, right click on the button, and select "Copy > Copy JS path".

That selector can be easily used in puppeteer.

Upvotes: 21

Related Questions