Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click element in Puppeteer using xPath

I want to click on an element without using css selectors.

await page.click()

uses selectors to identify the element.


So how can I do something like this?

await page.click('/*[@id="toc"]/ul/li[1]/a')
like image 450
Jozott Avatar asked Sep 24 '19 20:09

Jozott


People also ask

Can we use XPath in puppeteer?

In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element. For this, we have to use the xpath expression.

How do you click a link on a puppeteer?

Java Prime Pack Puppeteer is capable of handling a link/button on a page. Before clicking an element we must be able to uniquely identify it with the help of any of the locators. In Puppeteer, we can click an element only if its dimensions are greater than zero pixel.


1 Answers

First I had to get the element by using

await page.$x('<xPath>')

It returns an array with elements. To click I had to choose the first element in the array.

const elements = await page.$x('<xPath>')
await elements[0].click() 
like image 176
Jozott Avatar answered Sep 19 '22 00:09

Jozott