gpt4 book ai didi

javascript - 运行 Puppeteer 时出现 UnhandledPromiseRejectionWarning?

转载 作者:行者123 更新时间:2023-11-30 11:13:10 25 4
gpt4 key购买 nike

为什么我会收到以下警告,我该如何摆脱它们?

警告:

(node:26771) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Protocol error (Runtime.callFunctionOn): Target closed.

(node:26771) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zeroexit code.

代码:

const puppeteer = require("puppeteer");

(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://dn.se", { waitUntil: "domcontentloaded" });
var output = page.evaluate(() => {
return;
});
await browser.close();
})();

环境:

  • macOS High Sierra
  • Node v8.5.0
  • puppeteer 操纵者:1.9.0

最佳答案

您需要await page.evaluate() ,因为它返回一个 promise :

var output = await page.evaluate(() => {
return;
});

确保您使用的是 process.on('unhandledRejection')监听未处理的 promise 拒绝并在发生此类事件时优雅地关闭浏览器:

process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at: Promise', p, 'reason:', reason);
browser.close();
});

您的最终代码应如下所示:

'use strict';

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();

process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at: Promise', p, 'reason:', reason);
browser.close();
});

await page.goto('https://dn.se', {
waitUntil: 'domcontentloaded',
});

var output = await page.evaluate(() => {
return;
});

await browser.close();
})();

关于javascript - 运行 Puppeteer 时出现 UnhandledPromiseRejectionWarning?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com