猿问

如何显示给定 div 的所有结果,而不仅仅是一个 - puppeter

对不起,文档对我来说有点难以理解。


我使用的论点:


const myDiv = await page.$$eval(".myDiv", myDiv => myDiv.textContent);

但是 console.log 只会返回一个结果,而此 div 的结果 >10。


我如何显示它们?


编辑//这是我正在学习的代码


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();

})();


牧羊人nacy
浏览 143回答 3
3回答

拉莫斯之舞

您可以使用page.evaluate:const myDiv = await page.evaluate(() => {  const divs = Array.from(document.querySelectorAll('.myDiv'))  return divs.map(d => d.textContent)});传递给的函数page.evaluate将被序列化并发送到浏览器,因此它在浏览器上下文(而不是节点)中执行。

倚天杖

由于您没有提供更多代码,因此这个答案非常自以为是,可能无法解决您的问题。但它向您展示了一种了解正在发生的事情的方法。特别是在开发过程中,结合使用page.exposeFunction()和page.evaluate()来查看浏览器以及节点/木偶操纵者中发生的事情非常有帮助。这是一个草稿,我希望它能帮助你理解。(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.$$eval()在其回调中发送一个包含元素的数组,因此您需要这样的东西来获取所有元素数据:const myDivs = await page.$$eval(".myDiv", divs => divs.map(div => div.textContent));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答