[英]How to display all results for a given div, not just one - puppeter
对不起,但文档对我来说有点难以理解。
我使用的论点:
const myDiv = await page.$$eval(".myDiv", myDiv => myDiv.textContent);
但是当这个 div 的结果大于 10 时,console.log 只会返回一个结果。
我如何将它们全部显示出来?
编辑//这是我正在学习的代码
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();
})();
由于您没有提供更多代码,因此这个答案非常固执,可能无法解决您的问题。 但它向您展示了一种如何理解正在发生的事情的方法。
特别是在开发中,结合使用page.exposeFunction()
和page.evaluate()
来查看浏览器以及节点/puppeteer 中发生了什么非常有帮助。 这是一个草稿,希望能帮助你理解。
(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);
})();
您可以使用page.evaluate :
const myDiv = await page.evaluate(() => {
const divs = Array.from(document.querySelectorAll('.myDiv'))
return divs.map(d => d.textContent)
});
传递给 page.evaluate 的page.evaluate
将被序列化并发送到浏览器,因此它在浏览器上下文(而不是 Node)中执行。
page.$$eval()
在其回调中发送一个包含元素的数组,因此您需要这样的东西来获取所有元素数据:
const myDivs = await page.$$eval(".myDiv", divs => divs.map(div => div.textContent));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.