如何在puppeter中打印页面的控制台输出,就像在浏览器中一样? [英] How do print the console output of the page in puppeter as it would appear in the browser?

查看:112
本文介绍了如何在puppeter中打印页面的控制台输出,就像在浏览器中一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直看到此错误代码

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

失败

console.log('Hello %s', 'World');

产生

Hello World     // browser
Hello %s World  // puppeteer

好,所以我想也许我可以做到

Ok, So I thought maybe I could do this

page.on('console', msg => console.log(...msg.args()));

NOPE:那会丢掉一些巨大的 JSHandle 东西.

NOPE: That dumps out some giant JSHandle thing.

好吧,也许

page.on('console', msg => console.log(...msg.args().map(a => a.toString());

NOPE:可以打印

JSHandle: Hello %s JSHandle: World

我想可以删除前9个字符来破解它.

I suppose I can hack it by removing the first 9 characters.

我也尝试过

page.on('console', msg => console.log(...msg.args().map(a => a.jsonValue())));

NOPE:可以打印

Promise { <pending> } Promise { <pending> }

好吧

page.on('console', async(msg) => {
  const args = Promise.all(msg.args().map(a => a.jsonValue()));
  console.log(...args);
});

不是,可以打印

UnhandledPromiseRejectionWarning: TypeError: Found non-callable @@iterator
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 95)

另一个去

page.on('console', async(msg) => {
  const args = Promise.all(msg.args().map(async(a) => {
    return await a.jsonValue();
  }));
  console.log(...args);
});

与以前相同

UnhandledPromiseRejectionWarning: TypeError: Found non-callable @@iterator
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a 

我什至通过 msg.text()进行了跟踪,但是它所做的只是返回一个预制的字符串,因此使用该字符串为时已晚.

I even traced through msg.text() but all it does is return a premade string so it's too late to use that.

我如何获得与puppeteer中浏览器的console.log相同的输出?

How do I get the same output as the browser's console.log in puppeteer?

PS:如上所述,此hack在puppeteer 1.20.0中有效

PS: as mentioned above, this hack works in puppeteer 1.20.0

  page.on('console', (msg) => {
    console.log(...msg.args().map(v => v.toString().substr(9)));
  });

但这显然是一种破解,我希望它会在某个时候破解,因此需要寻找正确的解决方案.

but it's clearly a hack and I expect it will break at some point so looking for the correct solution.

推荐答案

  page.on('console', async e => {
    const args = await Promise.all(e.args().map(a => a.jsonValue()));
    console.log(...args);
  });

  page.on('console', async e => {
    const args = await Promise.all(e.args().map(a => a.jsonValue()));
    console[e.type() === 'warning' ? 'warn' : e.type()](...args);
  });

有效

这篇关于如何在puppeter中打印页面的控制台输出,就像在浏览器中一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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