Reputation: 301
I'm new for Puppeteer and I'm trying to get textContent from two divs that using same class.
<div class="post-item">
<div class="post-item-info">
<span class="post-item-status post-comment"></span>
3
</div>
<div class="post-item-info">
<span class="post-item-status post-vote"></span>
5
</div>
</div>
The result that I'm expecting is return an array [3,5]. My current code is below.
let postInfo = element.querySelector('.post-item-info');
The problem is it is only return the first one. Please let me know how to do it.
Upvotes: 3
Views: 11290
Reputation: 13822
Some concise ways to get the array of these text contents:
const texts = await page.$$eval('.post-item-info',
divs => divs.map(({ innerText }) => innerText));
const texts = await page.evaluate(() =>
[...document.querySelectorAll('.post-item-info')].map(({ innerText }) => innerText));
Upvotes: 3
Reputation: 3004
Well, there's a similar method for that querySelectorAll()
const nodes = document.querySelectorAll('.post-item-info')
Array.from(nodes).forEach(node => {
// do stuff with node
})
Upvotes: 2
Reputation: 4246
Your selector should be like const nodes = element.querySelectorAll('.post-item-info');
. Then to access individual items in the returned collection, use a traditional for loop like
for(let i = 0; i < nodes.length; i++){
const currentNode = nodes[i];
// doStuffWith(currentNode);
}
Upvotes: 4
Reputation: 6749
Get them like:
let elements = document.getElementsByClassName('post-item-info')
It returns an array and then you can loop on it. Also, you can see this Github question for the same case:
https://github.com/GoogleChrome/puppeteer/issues/461
Upvotes: 0