Klaus
Klaus

Reputation: 43

Puppeteer: select by class, but only first element

There are several div classes "jadejhlu" containing a a=href link. How can I select only the first div class to get only one link? I tried

const selector = 'div.jadejhlu > a'
const links = await page.$$eval(selector, am => am.filter(e => e.href).map(e => e.href))
console.log(links)

like it is explained here: Puppeteer - Retrieving links from divs with specific class names

I get a list of links. I could also try to extract the first link of this list. Or I could try to insert a [0] to select only the first div.

Any ideas? Thanks in advance.

Upvotes: 1

Views: 5698

Answers (2)

traynor
traynor

Reputation: 8667

use $eval instead:

const selector = 'div.jadejhlu > a'
const links = await page.$eval(selector, (el) => el.href);
console.log(links)

Upvotes: 2

Prophet
Prophet

Reputation: 33361

You can use nth-child method to select the first element only.
Something like this:

const selector = 'div.jadejhlu > a:nth-child(1)'

Upvotes: 1

Related Questions