首页 > 解决方案 > 在 Apify 中,如何从嵌套函数中登录到控制台?

问题描述

从 Apify 示例文档中,我可以看到,如果您使用console.log()within handlePageFunction,它会直接记录到终端控制台。Apify utils 也是如此log。例如:

handlePageFunction: async ({ request, page }) => {
    console.log('This is logged to the terminal console');
    log.info('So is this.')
    ...
}

但是,当我handlePageFunction 中定义自己的函数时,我无法将任何内容记录到终端控制台。我希望 console.log 会转到浏览器控制台,但在 Apify 中,浏览器窗口会迅速出现和消失。(也可以使用根本不显示浏览器的 apify-cli。)

handlePageFunction: async ({ request, page }) => {
  ...
  const myFunction = () => {
    console.log('This disappears into the ether.');
    log.info('This causes the script to fail with error, "log is not defined"');
  }
  myFunction();
}

如何在嵌套的 javascript 函数中使用 Apify utils.log?

标签: apify

解决方案


如果您page.evaluate在浏览器上下文中评估的 a 或任何其他函数中使用定义的函数,则会在浏览console.log器控制台中输出。如果您想让浏览器日志显示在 Node.js 中,这应该适用于简单的日志记录。-

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

推荐阅读