如何在Nightmare的evaluate()中向document.getElementById传递参数?
向Nightmare的evaluate方法传递参数问题
问题场景
我尝试运行带参数的checkPrice函数,代码如下:
const nightmare = require('nightmare')() let url = "https://www.amazon.co.uk/Guards-Discworld-City-Watch-Collection/dp/1473200180/" let identifier = "price" checkPrice(url, identifier) async function checkPrice(url2, identifier2) { console.log(identifier2) const priceString = await nightmare.goto(url2) .wait(`#${identifier2}`) .evaluate(() => document.getElementById(identifier2).innerText) .end() console.log(priceString) console.log("Hello!") }
运行时一直报这个错:UnhandledPromiseRejectionWarning: ReferenceError: identifier2 is not defined。但如果把document.getElementById(identifier2).innerText改成硬编码的document.getElementById("price").innerText,代码就能正常跑起来。
我想实现的是给document.getElementById()动态传参,试过硬编码值可行,但不符合函数的设计意图;也试过把identifier2放进字符串模板${identifier2},没解决问题。
原因及解决办法
这个报错的核心问题是:Nightmare的evaluate()方法里的回调函数是在浏览器的独立上下文里运行的,它没法直接拿到Node.js环境中定义的identifier2变量。
要给evaluate()的回调传参,得把参数作为evaluate()的后续参数传进去,然后在回调函数里接收使用。修改后的代码如下:
const nightmare = require('nightmare')() let url = "https://www.amazon.co.uk/Guards-Discworld-City-Watch-Collection/dp/1473200180/" let identifier = "price" checkPrice(url, identifier) async function checkPrice(url2, identifier2) { console.log(identifier2) const priceString = await nightmare.goto(url2) .wait(`#${identifier2}`) // 将identifier2作为参数传给evaluate,回调里用id接收 .evaluate((id) => document.getElementById(id).innerText, identifier2) .end() console.log(priceString) console.log("Hello!") }
简单说明:
evaluate()的第一个参数是要在浏览器里执行的回调,后面跟的参数会被传递给这个回调。- 回调里的
id就是我们传入的identifier2,这样就能在浏览器上下文里正确使用这个动态参数了。
内容的提问来源于stack exchange,提问作者user22422416
相关产品推荐
相关产品推荐

