Puppeteer:在 page.evaluate 中使用函数 [英] Puppeteer: use function inside page.evaluate
问题描述
我需要在 page.evaluate
中使用 puppeteer 中的函数.我使用 exposeFunction
并且我需要将完整的 Element 发送到我的函数
I need to use a function inside page.evaluate
with puppeteer. I use exposeFunction
and I need to send the full Element to my function
我有一个简单的例子:
const puppeteer = require('puppeteer');
const myFunction = (content) => {
console.log(content.outerHTML); // empty
}
(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
page.on('console', msg => console.log('PAGE LOG:', msg.text()));
const url = "https://www.google.com";
await page.goto(url,{
waitUntil: 'networkidle2'
})
await page.exposeFunction('myFunction', myFunction);
const content = await page.$('.content')
await page.evaluate( (content) => {
myFunction (content); // I need to send full Element
//console.log(content.outerHTML); // here works fine
//my_function (JSON.stringify(content)); // sends {}
}, content )
})()
我尝试使用 JSON.stringify/JSON.parse 发送但没有结果.
I've tried to send with JSON.stringify / JSON.parse with no results.
推荐答案
page.exposeFunction
仅限于序列化数据,正如其他答案已经指出的那样.
page.exposeFunction
is limited to serialized data as the other answer already points out.
但是您可以在 page.execute
块内定义一个函数.请注意,此处定义的函数只会出现在浏览器环境中,而不会出现在您的 Node.js 脚本中.
But you can define a function inside of the page.execute
block. Be aware, that functions defined there will only be present in the browser environment and not inside your Node.js script.
代码示例
以下代码在 evaluate
函数中实现了 myFunction
,然后可以在下面使用:
The following code implements the myFunction
inside the evaluate
function and can then be used below:
await page.evaluate((content) => {
const myFunction = (content) => {
return content.outerHTML;
};
const result = myFunction(content);
return result; // or whatever you want to do with the result
}, content);
这篇关于Puppeteer:在 page.evaluate 中使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!