How to select all child div with same class using Puppeteer?

时间秒杀一切 提交于 2021-02-10 13:58:08

问题


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.


回答1:


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);
    }



回答2:


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
})



回答3:


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));



回答4:


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



来源:https://stackoverflow.com/questions/54677126/how-to-select-all-child-div-with-same-class-using-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!