[英]How to display all results for a given div, not just one - puppeter
Excuse me, but the documentation is a little incomprehensible to me.对不起,但文档对我来说有点难以理解。
I use the argument:我使用的论点:
const myDiv = await page.$$eval(".myDiv", myDiv => myDiv.textContent);
but the console.log will only return one result while the results for this div are >10.但是当这个 div 的结果大于 10 时,console.log 只会返回一个结果。
How do I display them all?我如何将它们全部显示出来?
edit// That's my code that I'm learning from编辑//这是我正在学习的代码
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('mypage');
// await page.screenshot({path: 'example.png'});
await page.waitForSelector(".myDiv");
const myDiv = await page.$eval(".myDiv", myDiv => myDiv.textContent);
console.log(myDiv);
await browser.close();
})();
Since you did not provide more code, this answer is pretty opinionated and maybe doesn't solve your problem.由于您没有提供更多代码,因此这个答案非常固执,可能无法解决您的问题。 But it shows you a way how to understand what is happening.
但它向您展示了一种如何理解正在发生的事情的方法。
Exspecially in developement, it's very helpful to use a combination of page.exposeFunction()
and page.evaluate()
to see what is going on in the browser and also in node/puppeteer.特别是在开发中,结合使用
page.exposeFunction()
和page.evaluate()
来查看浏览器以及节点/puppeteer 中发生了什么非常有帮助。 Here is a draft which I hope it helps you to understand.这是一个草稿,希望能帮助你理解。
(async () => {
function executedInNodeContext(result) {
//this prints in the Node Console
console.log(result);
}
function executedInBrowserContext() {
console.log('Im in the Browser');
const myDiv = [...document.querySelectorAll('.myDiv')];
window.nameOfNodeFunction(myDiv);
}
// See the browser
const browser = await puppeteer.launch({ headless: false });
// Create a new page
const page = await browser.newPage();
// Callback in Node Context
await page.exposeFunction('nameOfNodeFunction', executedInNodeContext);
// Send puppeteer to a Url
await page.goto('http://localhost/awesome/URL');
// Function executed in the Browser on the given page
await page.evaluate(executedInBrowserContext);
})();
You can use page.evaluate :您可以使用page.evaluate :
const myDiv = await page.evaluate(() => {
const divs = Array.from(document.querySelectorAll('.myDiv'))
return divs.map(d => d.textContent)
});
Function passed to page.evaluate
will be serialized and sent to browser, so it is executed in browser context (not Node).传递给 page.evaluate 的
page.evaluate
将被序列化并发送到浏览器,因此它在浏览器上下文(而不是 Node)中执行。
page.$$eval()
sends in its callback an array with elements, so you need something like this to get all elements data: page.$$eval()
在其回调中发送一个包含元素的数组,因此您需要这样的东西来获取所有元素数据:
const myDivs = await page.$$eval(".myDiv", divs => divs.map(div => div.textContent));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.