![](/img/trans.png)
[英]How can I select a div in Javascript with only a class using puppeteer
[英]How to select all child div with same class using Puppeteer?
我是Puppeteer的新手,我正在尝试从使用相同类的两个div获取textContent。
<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>
我期望的结果是返回数组[3,5]。 我当前的代码如下。
let postInfo = element.querySelector('.post-item-info');
问题是它只返回第一个。 请让我知道该怎么做。
好吧,对于该querySelectorAll()有类似的方法
const nodes = document.querySelectorAll('.post-item-info')
Array.from(nodes).forEach(node => {
// do stuff with node
})
您的选择器应类似于const nodes = element.querySelectorAll('.post-item-info');
。 然后要访问返回的集合中的单个项目,请使用传统的for循环,例如
for(let i = 0; i < nodes.length; i++){
const currentNode = nodes[i];
// doStuffWith(currentNode);
}
一些简洁的方法来获取这些文本内容的数组:
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));
像这样得到它们:
let elements = document.getElementsByClassName('post-item-info')
它返回一个数组,然后可以在其上循环。 同样,您可以在相同情况下看到此Github问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.