You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何从Puppeteer返回的Promise提取实际值?

Puppeteer爬虫中提取Promise包裹的文本值问题解决

问题出在jsonValue()方法本身返回的是一个Promise,你直接赋值给text时,得到的是未完成解析的Promise对象,需要用await等待它解析完成才能拿到实际文本。

修改方案

  1. 在(await src).jsonValue()前添加await,解析Promise得到实际字符串
  2. 给browser.close()加上await,确保浏览器进程正常关闭,避免内存泄漏

修改后的完整代码

const puppeteer = require('puppeteer')
async function gatherContent(url){
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);
    const [el] = await page.$x('//*[@id="gatsby-focus-wrapper"]/div/header/h1/a');
    const src  = await el.getProperty('textContent');
    // 用await解析jsonValue返回的Promise
    const text = await (await src).jsonValue();
    // 直接赋值给其他变量即可
    const textAgain = text;
    console.log({text, textAgain});       
    await browser.close();    
}
gatherContent('https://returnstring.com/articles/puppeteer-elements-and-values')

运行结果

执行node scrap.js后,控制台会输出:

{ text: 'Return String', textAgain: 'Return String' }

此时textAgain已经成功获取到Promise包裹的实际内容。

可选:拆分步骤提升可读性

如果觉得嵌套的await不够直观,可以拆分成多行:

const src = await el.getProperty('textContent');
const textHandle = await src.jsonValue();
const text = textHandle;
const textAgain = text;

内容的提问来源于stack exchange,提问作者Helper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:01:06