javascript Puppeteer 登录 page.evaluate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46198527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:31:27  来源:igfitidea点击:

Puppeteer log inside page.evaluate

javascriptnode.jspuppeteer

提问by Alex Arvanitidis

How can I console.log something inside the page.evaluate, passing it to node and using it duringthe evaluation of the page?

如何在 page.evaluate 中 console.log 某些内容,将其传递给 node 并在页面评估期间使用它?

I actually want to log the progress of the page.evaluate to the console and show some results to the user.

我实际上想将 page.evaluate 的进度记录到控制台并向用户显示一些结果。

回答by Vaviloff

**Updated to work with puppeteer v1.4.x

**更新以与 puppeteer v1.4.x 一起使用

If all you want is to "log the progress of the page.evaluate to the console", then just

如果您只想“将页面的进度记录到控制台。评估到控制台”,那么只需

const page = await browser.newPage();

page.on('console', consoleObj => console.log(consoleObj.text()));

And use console.login page.evaluateas usual, no more dependencies are required.

和使用console.logpage.evaluate像往常一样,不需要更多的依赖关系。

Also see this nice tweakto remove multiple annoying warnings from log.

另请参阅这个很好的调整以从日志中删除多个烦人的警告。

回答by Jam Risser

The easiest way to get it to work exactly like you'd expect

让它像您期望的那样工作的最简单方法

const page = await browser.newPage();
page.on('console', (log) => console[log._type](log._text));

回答by Nicolas Bouvrette

A lot of the answers provided previously no longer work today. Also one thing that can be very annoying on some pages, is the "warning" messages which pollutes the output. One way to fix that is to filter for the type of the message. The following code helps reduce the noise and works with current versions of Puppeteer:

以前提供的许多答案今天不再适用。在某些页面上还有一件非常烦人的事情是污染输出的“警告”消息。解决这个问题的一种方法是过滤消息的类型。以下代码有助于降低噪音并适用于当前版本的 Puppeteer:

const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', consoleMessageObject => function (consoleMessageObject) {
    if (consoleMessageObject._type !== 'warning') {
        console.debug(consoleMessageObject._text)
    }
});

await page.goto('https://google.com');
const result = await page.evaluate(() => {
    console.log('Browser scope.');
    return 'Normal scope.';
});
console.log(result)

回答by Paul

Implement the notifyUifunction in this code sample:

实现notifyUi此代码示例中的功能:

const page = await browser.newPage();
page.on('console', (...args) => {
    this.notifyUi('[chrome] ' + args[0]);
});
await page.goto(url);
const result = await page.evaluate(() => {
    console.log('I am alive');
    return Promise.resolve(true);
});
this.notifyUi('Evaluation returned with ' + result);

回答by John Vandivier

I like @Vaviloff's answer, but you will log the whole ConsoleMessage object when you may just want the text. Thus, I personally use the below:

我喜欢@ Vaviloff的回答,但是当您可能只需要文本时,您将记录整个 ConsoleMessage 对象。因此,我个人使用以下内容:

const EOL = require('os').EOL;
const _page = await browser.newPage();

_page.on('console', _fCleanLog);

function _fCleanLog(ConsoleMessage) {
    console.log(ConsoleMessage.text + EOL);
}

回答by Hyung Doe

const page = await browser.newPage();
page.on("console", msg => {
for (let i = 0; i < msg.args().length; ++i)
console.log(`${i}: ${msg.args()[i]}`);
});

try this one if none of the above works. shows no error logs but only the log I created.

如果上述方法均无效,请尝试此方法。不显示错误日志,只显示我创建的日志。

回答by raphaeli

Update for version 1.15.x and above - Jan 2020

1.15.x 及更高版本的更新 - 2020 年 1 月

In the latest version args has been replaced with _args.

在最新版本中,args 已被替换为 _args。

So when you are using page.evaluate()or page.evaluateHandle()and you want to get the console.log()text from the browser context back to node, use the following code and make sure to set the listener before any console.log()calls:

因此,当您使用page.evaluate()orpage.evaluateHandle()并且希望将console.log()文本从浏览器上下文返回到节点时,请使用以下代码并确保在任何console.log()调用之前设置侦听器:

Code:

代码:

    // First we register our listener.
    page.on('console', msg => {
    for (let i = 0; i < msg._args.length; ++i)
        console.log(`${i}: ${msg._args[i]}`);
    });

    // Then we call the log.
    page.evaluate(() => console.log('Hello World'));

Explanation:

解释:

You can't see the console.log()text in your node console or set node breakpoints inside page.evaluate()or page.evaluateHandle(), because the code inside those functions is running only in the browser context. If you would launch puppeteer in none headless mode you would see the console.log()message showing in the browser.

你不能看到console.log()文字里面的节点控制台或组节点断点page.evaluate()或者page.evaluateHandle(),因为这些功能中的代码仅在浏览器上下文中运行。如果您在无头模式下启动 puppeteer,您将看到console.log()浏览器中显示的消息。

Sidenote:

边注:

In most cases you don't really need to log inside the browser context and you can do the same work in the 'Console' tab of your browser 'Developer tools' section.

在大多数情况下,您实际上并不需要登录浏览器上下文,您可以在浏览器“开发人员工具”部分的“控制台”选项卡中执行相同的工作。

回答by Abdullah Al Maruf - Tuhin

I am trying to share my workaround if it helps anybody in future.

如果将来对任何人有帮助,我会尝试分享我的解决方法。

  1. Print all the console outputs to stdout including warning, error, log:

    page = await browser.newPage();
    page.on("console", (consoleObj) => console.log(consoleObj.text()));
    
  2. Print everything except warning:

    page.on('console', consoleObj => {
        if (consoleObj.type() !== 'warning') {
            console.log(consoleObj.text());
        }
    })
    
  3. Print only logs (Ex: console.logs).

    page.on('console', consoleObj => {
        if (consoleObj.type() === 'log') {
            console.log(consoleObj.text());
        }
    })
    
  1. 将所有控制台输出打印到标准输出,包括警告、错误、日志:

    page = await browser.newPage();
    page.on("console", (consoleObj) => console.log(consoleObj.text()));
    
  2. 打印除警告外的所有内容:

    page.on('console', consoleObj => {
        if (consoleObj.type() !== 'warning') {
            console.log(consoleObj.text());
        }
    })
    
  3. 仅打印日志(例如:)console.logs

    page.on('console', consoleObj => {
        if (consoleObj.type() === 'log') {
            console.log(consoleObj.text());
        }
    })
    

The last one helped me more to debug efficiently.

最后一个帮助我更有效地调试。

回答by E. Fortes

const page = await browser.newPage();
page.on('console', ConsoleMessage => console.log(ConsoleMessage.text));