您好,我一直尝试运行 puppeteer 测试,但不断遇到此问题。请帮忙谢谢。 enter image description here 代码:
import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://developers.google.com/web/');
// Type into search box.
await page.type('.devsite-search-field', 'Headless Chrome');
// Wait for suggest overlay to appear and click "show all results".
const allResultsSelector = '.devsite-suggest-all-results';
await page.waitForSelector(allResultsSelector);
await page.click(allResultsSelector);
// Wait for the results page to load and display the results.
const resultsSelector = '.gsc-results .gs-title';
await page.waitForSelector(resultsSelector);
// Extract the results from the page.
const links = await page.evaluate(resultsSelector => {
return [...document.querySelectorAll(resultsSelector)].map(anchor => {
const title = anchor.textContent.split('|')[0].trim();
return `${title} - ${anchor.href}`;
});
}, resultsSelector);
// Print all the files.
console.log(links.join('\n'));
await browser.close();
})();
错误:
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:74:18)
at wrapSafe (node:internal/modules/cjs/loader:1128:20)
at Module._compile (node:internal/modules/cjs/loader:1169:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
at Module.load (node:internal/modules/cjs/loader:1068:32)
at Module._load (node:internal/modules/cjs/loader:909:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
我尝试重新安装 Node js 和 npm,但没有任何效果。
最佳答案
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
在 package.json 文件中添加 type:module 或安装最新的 Nodejs
关于node.js - 语法错误: Cannot use import statement outside a module using puppeteer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74650098/