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
相关产品推荐
相关产品推荐

