Nodejs/Puppeteer - How to use page.evaluate

烂漫一生 提交于 2019-12-22 09:57:50

问题


I know is a noob question, but I want to know when I should use page.evaluate

I also know the documentation exists, but I still do not understand

Can anybody give me an explanation about how and when to use this function when creating a scraper with puppeteer?


回答1:


First, it is important to understand that there are two main environments:

  • Node.js (Puppeteer) Environment
  • Page DOM Environment

You should use page.evaluate() when you are seeking to interact with the page directly in the page DOM environment by passing a function and returning a <Promise<Serializable>> which resolves to the return value of the passed function.

Otherwise, if you do not use page.evaluate(), you will be dealing with elements as an ElementHandle object in the Node.js (Puppeteer) environment.

Example Usage:

const example = await page.evaluate(() => {
  const elements = document.getElementsByClassName('example');
  const result = [];

  document.title = 'New Title';

  for (let i = 0; i < elements.length; i++) {
    result.push(elements[i].textContent);
  }

  return JSON.stringify(result);
});

See the simplified diagram below:



来源:https://stackoverflow.com/questions/52045947/nodejs-puppeteer-how-to-use-page-evaluate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!