我一直看到这个错误的代码
page.on('console', msg => console.log(msg.text()));
那个失败了
console.log('Hello %s', 'World');
产生Hello World // browser
Hello %s World // puppeteer
好的,所以我想也许我可以做到这一点
page.on('console', msg => console.log(...msg.args()));
不对:它会输出一个庞大的JSHandle
对象。
好的,那么也许
page.on('console', msg => console.log(...msg.args().map(a => a.toString());
不行:那会输出
JSHandle: Hello %s JSHandle: World
我想我可以通过删除前9个字符来解决它。
我还尝试过
page.on('console', msg => console.log(...msg.args().map(a => a.jsonValue())));
不行:那会打印出来
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()
,但它只是返回一个预制的字符串,所以现在使用它已经太迟了。
如何在Puppeteer中获得与浏览器的console.log相同的输出结果?
附注:如上所述,此方法适用于Puppeteer 1.20.0。
page.on('console', (msg) => {
console.log(...msg.args().map(v => v.toString().substr(9)));
});
但显然这是一个hack,我期望它在某个时候会出现问题,因此正在寻找正确的解决方案。
msg.args().map(v => v.toString().substr(9))
来获取它们,但这似乎是一种hack方法,因此我想知道正确的方法是什么。 - gman