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

NightmareJS中使用getElementsByClassName获取价格仅返回元素对象怎么办?

你当前获取到的是a-offscreen对应的DOM元素对象本身,并非元素内的文本内容,直接返回DOM对象序列化后就会得到[object HTMLSpanElement]的输出。你需要读取元素的textContent属性即可拿到价格文本。

修改后的代码如下:

import Nightmare from 'nightmare'
const nightmare = Nightmare({ show: true })
nightmare
    .goto('https://www.amazon.com/')
    .insert("input[aria-label='Search']", 'impressora')
    .click("input[value='Go']")
    // 优化:等待目标元素出现再执行后续操作,比固定等待2秒更稳定
    .wait('.a-offscreen')
    .evaluate(function(){
        // 获取元素后读取textContent属性,加判空避免元素不存在时报错
        const targetEle = document.getElementsByClassName('a-offscreen')[0];
        return targetEle ? targetEle.textContent.trim() : '未找到价格元素';
    }).then(function (price)  {
        console.log('Price:', price)
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:54:03