gpt4 book ai didi

Puppeteer:在 page.evaluate 中使用函数

转载 作者:行者123 更新时间:2023-12-05 08:52:33 29 4
gpt4 key购买 nike

我需要在 page.evaluate 中使用 puppeteer 中的一个函数。我使用 exposeFunction 并且我需要将完整的元素发送到我的函数

我有一个简单的例子:

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 发送但没有结果。

最佳答案

page.exposeFunction 仅限于序列化数据,正如其他答案已经指出的那样。

但是您可以在 page.execute block 中定义一个函数。请注意,此处定义的函数只会存在于浏览器环境中,而不存在于您的 Node.js 脚本中。

代码示例

以下代码在 evaluate 函数中实现了 myFunction,然后可以在下面使用:

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 中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458399/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com