【发布时间】:2019-01-25 05:19:21
【问题描述】:
在以下代码示例中,作为参数传递给page.evaluate() 的函数内部的日志语句不会打印到节点控制台(终端)。此函数之外的日志语句(最后)正在按预期打印。
另一位程序员建议,page.evaluate 上下文可能是无头浏览器环境,而不是 Node.js。
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setExtraHTTPHeaders({Referer: 'https://sparktoro.com/'});
await page.goto('https://sparktoro.com/trending');
await page.waitForSelector('div.title > a');
const stories = await page.evaluate(() => {
const selection = document.querySelectorAll('div.title > a');
console.log('selection', selection);
const links_array = Array.from(selection);
console.log('links_array', links_array);
const hrefs = links_array.map(anchor => anchor.href)
console.log('hrefs', hrefs);
return hrefs
});
console.log(stories);
await browser.close();
})();
有什么方法可以强制所有 console.log 语句使用 Node 环境作为它们的上下文,还是我唯一的选择是启用浏览器头并从浏览器控制台读取语句?
【问题讨论】:
标签: javascript node.js puppeteer