page.$$ and ElementHandle traversal
Emily Wong
After reading the documentation and the examples I still have problems of understanding how one can navigate through ElementHandle response of page.$$.
Most of the use cases of wanting to use page.$$ and implicitly document.querySelectorAll() are to get an array or a NodeList and then work on top of that.
Let's say we have a page with 5 links and I want to print the href of the 2nd a in my script. This is what I've tried and it doesn't work.
const linksArray = await page.$$('a');
const the2ndHref = await page.evaluate(linkList => linkList[1].href, linksArray);
console.log('the2ndHref', the2ndHref);
await linksArray.dispose();Can you please help?
1 Answer
My guess is that you dont actually want an ElementHandle because an ElementHandle represents a DOM element where you can actuate with properties like click, focus, hover.
If you want to get the href of links, you can do something like this:
await page.goto(')
const LINKS_SELECTOR = 'a'
const the2ndHref = await page.evaluate(selector => { const allLinks = document.querySelectorAll(selector) return allLinks[1].href
}, LINKS_SELECTOR)
console.log('the2ndHref', the2ndHref) 0