问题描述
我正在尝试实现一些非常琐碎的事情:获取元素列表,然后使用每个元素的innerText
进行操作.
I'm trying to achieve something very trivial: Get a list of elements, and then do something with the innerText
of each element.
const tweets = await page.$$('.tweet');
据我所知,这将返回一个节点列表,就像浏览器中的document.querySelectorAll()
方法一样.
From what I can tell, this returns a nodelist, just like the document.querySelectorAll()
method in the browser.
我如何遍历它并得到我所需要的?我尝试了各种东西,例如:
How do I just loop over it and get what I need? I tried various stuff, like:
[...tweets].forEach(tweet => {
console.log(tweet.innerText)
});
推荐答案
page.$$():
您可以结合使用 elementHandle.getProperty()
和 jsHandle.jsonValue()
来获取 innerText
来自 ElementHandle
GoogleChrome/puppeteer/blob/master/docs/api.md#pageselector-1"rel =" noreferrer> page.$$()
:
page.$$():
You can use a combination of elementHandle.getProperty()
and jsHandle.jsonValue()
to obtain the innerText
from an ElementHandle
obtained with page.$$()
:
const tweets = await page.$$('.tweet');
for (let i = 0; i < tweets.length; i++) {
const tweet = await (await tweets[i].getProperty('innerText')).jsonValue();
console.log(tweet);
}
如果您设置使用 forEach()
方法,您可以将循环包装在promise中:
If you are set on using the forEach()
method, you can wrap the loop in a promise:
const tweets = await page.$$('.tweet');
await new Promise((resolve, reject) => {
tweets.forEach(async (tweet, i) => {
tweet = await (await tweet.getProperty('innerText')).jsonValue();
console.log(tweet);
if (i === tweets.length - 1) {
resolve();
}
});
});
page.evaluate():
或者,您可以使用 page.$$()
,并使用 page.evaluate()
:
page.evaluate():
Alternatively, you can skip using page.$$()
entirely, and use page.evaluate()
:
const tweets = await page.evaluate(() => Array.from(document.getElementsByClassName('tweet'), e => e.innerText));
tweets.forEach(tweet => {
console.log(tweet);
});
这篇关于木偶:如何获取节点列表中每个元素的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!