How Do Print the Console Output of the Page in Puppeter as It Would Appear in the Browser

How do print the console output of the page in puppeter as it would appear in the browser?

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

or

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

works

Puppeteer log inside page.evaluate

Update for puppeteer 12, adapted from the current documentation:

page.on('console', async (msg) => {
const msgArgs = msg.args();
for (let i = 0; i < msgArgs.length; ++i) {
console.log(await msgArgs[i].jsonValue());
}
});

await page.evaluate(() => console.log('hello', 5));
await page.evaluate(() => console.log({ foo: 'bar' }));
await page.evaluate(() => console.log([1, 2, 3, 4, 5]));

Shows the following results:

hello  
5
{ foo: 'bar' }
[ 1, 2, 3, 4, 5 ]

How to print an HTML document using Puppeteer?

fs.writeFile()

You can use the following write_file function that returns a Promise that resolves or rejects when fs.writeFile() succeeds or fails.

Then, you can await the Promise from within your anonymous, asynchronous function and check whether or not the data was written to the file:

'use strict';

const fs = require('fs');
const puppeteer = require('puppeteer');

const write_file = (file, data) => new Promise((resolve, reject) => {
fs.writeFile(file, data, 'utf8', error => {
if (error) {
console.error(error);
reject(false);
} else {
resolve(true);
}
});
});

(async () => {

// ...

const stores = await page.evaluate(() => {
return Array.from(document.querySelectorAll('div.info > a.tit'), link => link.innerText).slice(0, 10); // 10개 제품만 가져오기
});

if (await write_file('example.html', stores.toString()) === false) {
console.error('Error: Unable to write stores to example.html.');
}

// ...

});

Puppeteer evaluate function on load to show alert

page.goto already waits for the page to load, so by the time your evalute runs, you can't re-wait for the page to load, so the load event will never fire.

Another problem is that document.alert isn't a function. You may be thinking of document.write or window.alert. In any case, neither function is particularly useful for debugging, so I suggest sticking to console.log unless you have a very compelling reason not to.

When working with Puppeteer, it's important to isolate problems by running your evaluate code by hand in the browser without Puppeteer, otherwise you might have no idea whether it's Puppeteer that's failing, or just plain old bad browser code.

Anything logged in evaluate won't be shown in your Node stdout or stderr, so you'll probably want to monitor that with a log listener. You'll need to look at both Node and the browser console for errors.

Depending on what you're trying to accomplish, page.evaluateOnNewDocument(pageFunction[, ...args]) will let you attach code to evaluate whenever you navigate, which might be what you're trying for here.

Here's an example of alerting headfully:

const puppeteer = require("puppeteer");

let browser;
(async () => {
browser = await puppeteer.launch({headless: false});
const [page] = await browser.pages();
await page.evaluateOnNewDocument(() => {
window.addEventListener("load", event => {
alert("Loaded!");
});
});
await page.goto("https://bet254.com", {waitUntil: "networkidle0"});
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;

Using console.log:

const puppeteer = require("puppeteer");

const onPageConsole = msg =>
Promise.all(msg.args().map(e => e.jsonValue()))
.then(args => console.log(...args))
;

let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
page.on("console", onPageConsole);
await page.evaluateOnNewDocument(() => {
window.addEventListener("load", event => {
alert("Loaded!");
});
});
await page.goto("https://bet254.com", {waitUntil: "networkidle0"});
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;

If all you're trying to do is run some code after load, then you might not even need to be attaching a listener to the load event at all:

const puppeteer = require("puppeteer");

const onPageConsole = msg =>
Promise.all(msg.args().map(e => e.jsonValue()))
.then(args => console.log(...args))
;

let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
page.on("console", onPageConsole);
await page.goto("https://bet254.com", {waitUntil: "networkidle0"});
await page.evaluate(() => console.log("Loaded!"));
})()
.catch(err => console.error(err))
.finally(async () => await browser.close())
;

Why console.log in puppeteer page.evaluate doesn't work?

Add the following to see the browser's console log:

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


Related Topics



Leave a reply



Submit