简体   繁体   English

无法在无头浏览器中读取控制台日志

[英]Cant read console logs in a headless browser

Im running puppeteer in a node js project to try and get the console logs of a URL.我在 node js 项目中运行 puppeteer 以尝试获取 URL 的控制台日志。 It only seems to work with the initial console logs at startup that arn't warnings or errors.它似乎只适用于启动时没有警告或错误的初始控制台日志。

What I would like is to view all of the logs just like you would in a normal browser for the first x amount of seconds.我想要的是在前 x 秒内像在普通浏览器中一样查看所有日志。 Here is my code:这是我的代码:

const puppeteerOptions =
{
    headless: true,
    args: ['--disable-gpu', '--disable-dev-shm-usage', '--disable-setuid-sandbox', '--no-first-run', '--no-sandbox', '--no-zygote', '--single-process'],
};

(async () =>
    {
        try
        {
            const browser = await HeadlessBrowser.launch(puppeteerOptions);
            const page = await browser.newPage();

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

            await page.goto('https://uk.yahoo.com/');
            await browser.close();
        }
        catch(e) {return reject(e);}
    })();

In this case im going to the yahoo site which contains lots of console logs but doesnt display any here.在这种情况下,我会访问 yahoo 站点,该站点包含大量控制台日志,但此处不显示任何内容。 I think its because they are logging after the site has loaded.我认为这是因为他们在网站加载后登录。

As for reading the logs in the first x amount of seconds, I have tried adding this before closing the browser but all that did was stall the closing and no console logs came through.至于在前 x 秒内读取日志,我尝试在关闭浏览器之前添加它,但所做的只是阻止关闭并且没有控制台日志通过。

await page.waitFor(10000);等待 page.waitFor(10000);

I managed to fix this and here is the correct way.我设法解决了这个问题,这是正确的方法。

const delay = 5000; //Milliseconds, 5 seconds

(async () =>
    {
        try
        {
            const browser = await HeadlessBrowser.launch(puppeteerOptions);
            const page = await browser.newPage();

            page.on('console', msg =>
            {
                //do whatever
            });

            page.on('pageerror', error =>
            {
                // do whatever
            });

            /*
            page.on('requestfailed', request => {
                //Didn't need
            });
            */

            await page.goto(data.url);
            await page.waitFor(delay);
            await browser.close();

            Utils.logger('Finished reading console logs.');
            return resolve();
        }
        catch(e) {return reject(e);}
    })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM