如何在Puppeteers .evaluate()方法中传递函数? [英] How to pass a function in Puppeteers .evaluate() method?

查看:281
本文介绍了如何在Puppeteers .evaluate()方法中传递函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我尝试传递一个函数时,就像这样:

Whenever I try to pass a function, like this:

var myFunc = function() { console.log("lol"); };

await page.evaluate(func => {
 func();
 return true;
}, myFunc);

我得到:

(node:13108) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: TypeError: func is not a function
at func (<anonymous>:9:9)
(node:13108) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

为什么?如何正确执行?

Why? How to do it correctly?

谢谢!

€:让我澄清一下:我这样做是因为我想先找到一些DOM元素,然后在该函数内部使用它们,就像这样(简化):

€: let me clarify: I am doing it this way because I want to find some DOM elements first and use them inside of that function, more like this (simplified):

var myFunc = function(element) { element.innerHTML = "baz" };

await page.evaluate(func => {
  var foo = document.querySelector('.bar');
  func(foo);
  return true;
}, myFunc);

推荐答案

伪造者有几种方法可以解决您的问题.首先要保持简单.

There are several way to deal with your problem. First rule is to keep it simple.

这是最快的处理方式,您只需传递函数并执行它即可.

This is the fastest way to do things, you can just pass the function and execute it.

await page.evaluate(() => {
  var myFunc = function(element) { element.innerHTML = "baz" };
  var foo = document.querySelector('.bar');
  myFunc(foo);
  return true;
});

预先暴露功能

您可以预先使用page.evaluate或page.addScriptTag

Expose the function beforehand

You can expose the function beforehand using a page.evaluate, or a page.addScriptTag

// add it manually and expose to window
await page.evaluate(() => {
  window.myFunc = function(element) { element.innerHTML = "baz" };
});

// add some scripts
await page.addScriptTag({path: "myFunc.js"});

// Now I can evaluate as many times as I want
await page.evaluate(() => {
  var foo = document.querySelector('.bar');
  myFunc(foo);
  return true;
});

使用ElementHandle

页面.$(选择器)

您可以将元素句柄传递给.evaluate并根据需要进行更改.

Use ElementHandle

page.$(selector)

You can pass an element handle to .evaluate and make changes as you seem fit.

const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);

page.$ eval

您可以定位一个元素并根据需要进行更改.

page.$eval

You can target one element and make changes as you want.

const html = await page.$eval('.awesomeSelector', e => {
e.outerHTML = "whatever"
});

诀窍是阅读文档并将其保留简单.

The trick is to read the docs and keep it simple.

这篇关于如何在Puppeteers .evaluate()方法中传递函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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