Puppeteer:在 page.evaluate 中使用函数

标签 puppeteer

我需要在 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/

相关文章:

javascript - JavaScript 中 &= 的含义是什么

jestjs - 预设 Jest puppeteer 无效

javascript - 是否可以将函数传递给 Puppeteer 的 page.evaluate()

javascript - puppeteer 师 : Timeout or sleep or wait inside Page. 评估()

google-chrome - chrome DevTools 协议(protocol)中的浏览器目标是什么?

node.js - 网页抓取某些网页无法完成

javascript - 使用 puppeteer 的提示

javascript - 使用 Puppeteer 响应 Chrome 的通知

javascript - 如何使用 Node JS Puppeteer 在我的 headless chrome 请求中设置代理服务器