[英]How to select all child div with same class using Puppeteer?
I'm new for Puppeteer and I'm trying to get textContent from two divs that using same class. 我是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>
The result that I'm expecting is return an array [3,5]. 我期望的结果是返回数组[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.
请让我知道该怎么做。
Well, there's a similar method for that querySelectorAll() 好吧,对于该querySelectorAll()有类似的方法
const nodes = document.querySelectorAll('.post-item-info')
Array.from(nodes).forEach(node => {
// do stuff with node
})
Your selector should be like const nodes = element.querySelectorAll('.post-item-info');
您的选择器应类似于
const nodes = element.querySelectorAll('.post-item-info');
. 。 Then to access individual items in the returned collection, use a traditional for loop like
然后要访问返回的集合中的单个项目,请使用传统的for循环,例如
for(let i = 0; i < nodes.length; i++){
const currentNode = nodes[i];
// doStuffWith(currentNode);
}
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));
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:
同样,您可以在相同情况下看到此Github问题:
https://github.com/GoogleChrome/puppeteer/issues/461 https://github.com/GoogleChrome/puppeteer/issues/461
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.