Home > Mobile >  Puppeteer: select by class, but only first element
Puppeteer: select by class, but only first element

Time:01-21

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.

CodePudding user response:

use $eval instead:

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

CodePudding user response:

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

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