有没有办法添加脚本来在chrome + puppeeter的evaluate()上下文中添加新函数? [英] Is there a way to add script to add new functions in evaluate() context of chrome+puppeeter?

查看:214
本文介绍了有没有办法添加脚本来在chrome + puppeeter的evaluate()上下文中添加新函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此回复,有没有办法(比如使用casperjs / phantomjs)在page.evaluate()上下文中添加我们的自定义函数?

Based on this response, is there a way (like with casperjs/phantomjs) to add our custom functions in page.evaluate() context ?

例如,包含一个文件调用Xpath函数的辅助函数 x x('// a / @ href')

By example, include a file with a helper function x to call an Xpath function : x('//a/@href')

推荐答案

您可以在单独的 page.evaluate()中注册帮助函数功能。 page.exposeFunction() 看起来很诱人,但无权访问浏览器上下文(您需要文档对象)。

You can register helper functions in separate page.evaluate() function. page.exposeFunction() looks temptingly, but it don't have access to browser context (and you need document object).

以下是使用 $ x()注册帮助函数的示例:

Here is an example of registering helper function with $x():

const puppeteer = require('puppeteer');

const helperFunctions = () => {
    window.$x = xPath => document
        .evaluate(
            xPath,
            document,
            null,
            XPathResult.FIRST_ORDERED_NODE_TYPE,
            null
        )
        .singleNodeValue;
};

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://en.wikipedia.org', { waitUntil: 'networkidle2' });

    await page.evaluate(helperFunctions);

    const text = await page.evaluate(() => {
        // $x() is now available
        const featureArticle = $x('//*[@id="mp-tfa"]');

        return featureArticle.textContent;
    });
    console.log(text);
    await browser.close();
})();






(编辑 - 添加帮助文件)

您还可以将帮助程序保存在单独的文件中,并通过 page.addScriptTag()
下面是一个例子:

You can also keep helpers in a separate file and inject it into browser context by page.addScriptTag(). Here is an example of it:

helperFunctions.js

window.$x = xPath => document
    .evaluate(
        xPath,
        document,
        null,
        XPathResult.FIRST_ORDERED_NODE_TYPE,
        null
    )
    .singleNodeValue;

并使用它:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://en.wikipedia.org', { waitUntil: 'networkidle2' });

    await page.addScriptTag({ path: './helperFunctions.js' });

    const text = await page.evaluate(() => {
        // $x() is now available
        const featureArticle = $x('//*[@id="mp-tfa"]');

        return featureArticle.textContent;
    });
    console.log(text);
    await browser.close();
})();

这篇关于有没有办法添加脚本来在chrome + puppeeter的evaluate()上下文中添加新函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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