Nodejs/Puppeteer - 如何使用 page.evaluate [英] Nodejs/Puppeteer - How to use page.evaluate

查看:93
本文介绍了Nodejs/Puppeteer - 如何使用 page.evaluate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个菜鸟问题,但我想知道什么时候应该使用 page.evaluate

我也知道文档存在,但我还是不明白

有人可以解释一下在使用 puppeteer 创建刮板时如何以及何时使用此功能吗?

解决方案

首先,重要的是要了解有两个主要环境:

  • Node.js (Puppeteer) 环境
  • 页面 DOM 环境

你应该使用

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?

解决方案

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:

这篇关于Nodejs/Puppeteer - 如何使用 page.evaluate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆