我正在使用 puppeteer 库来进行一些网页抓取。我想将异步对象返回到调用它的外部函数,以便我可以将其插入到我的数据库中。
问题是,为了处理异步函数正在操作的浏览器对象,您必须调用“await browser.close();”作为最后一次通话。
另一个问题是,控制台记录我的函数结果仅显示一个 promise 。
我尝试将 return 语句放在 wait browser.close() 方法之后,以及放置“return wait mainObj”,但它仍然返回一个 promise 。
const puppeteer = require('puppeteer');
async function webScraper(u, p, url) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
await page.waitForSelector('#UserName')
await page.focus('#UserName')
await page.keyboard.type(u)
await page.waitForSelector('#Password')
await page.focus('#Password')
await page.keyboard.type(p)
// Code edited out to keep private what website I'm using.
// Here it loops through page contents and constructs arrays which are used to construct my mainObj.
let mainObj = {};
let secondObj = {};
for (i = 0; i < descArray.length; i++) {
secondObj[descArray[i]] = [ammtArray[i], datesArray[i]]
}
secondObj[totaldescArray[0]] = totalammtArray[0]
mainObj[datesArray[0]] = secondObj
console.log(mainObj, 'here')
await browser.close();
return await mainObj
}
console.log(webScraper("username", "password", "url"))
Console.logging 函数中的 mainObj 返回我期望的对象。但是 console.logging 调用函数 webScraper() 的结果返回一个 Promise。无论我是否使用“return wait mainObj”或“return mainObj”(请记住,等待对象是因为构造数组的省略部分是异步的)。
有人可以指出我做错了什么吗?谢谢。
最佳答案
也许您应该等待从 webScraper
返回的 Promise 来完成处理。由于您无法在 async
函数之外使用 await
,因此请使用 Promise.then
:
webScraper("username", "password", "url")
.then(mainObj => console.log(mainObj));
关于javascript - 如何从 puppeteer 异步函数内部返回值(对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57575889/