如何使用 Puppeteer select 所有 child div 和相同的 class?
How to select all child div with same class using Puppeteer?
我是 Puppeteer 的新手,我正在尝试从两个使用相同 class 的 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>
我期待的结果是 return 数组 [3,5]。我当前的代码如下。
let postInfo = element.querySelector('.post-item-info');
问题是它只是 return 第一个。请告诉我该怎么做。
嗯,有一个类似的方法querySelectorAll()
const nodes = document.querySelectorAll('.post-item-info')
Array.from(nodes).forEach(node => {
// do stuff with node
})
让他们喜欢:
let elements = document.getElementsByClassName('post-item-info')
它 returns 一个数组然后你可以在它上面循环。此外,您还可以看到针对同一案例的 Github 问题:
您的选择器应该像 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));
我是 Puppeteer 的新手,我正在尝试从两个使用相同 class 的 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>
我期待的结果是 return 数组 [3,5]。我当前的代码如下。
let postInfo = element.querySelector('.post-item-info');
问题是它只是 return 第一个。请告诉我该怎么做。
嗯,有一个类似的方法querySelectorAll()
const nodes = document.querySelectorAll('.post-item-info')
Array.from(nodes).forEach(node => {
// do stuff with node
})
让他们喜欢:
let elements = document.getElementsByClassName('post-item-info')
它 returns 一个数组然后你可以在它上面循环。此外,您还可以看到针对同一案例的 Github 问题:
您的选择器应该像 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));