我正在尝试使用传入的参数运行我的 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未定义”。
如果我将 document.getElementById(identifier2).innerText) 更改为 document.getElementById("price").innerText) 那么它就可以正常工作。
有什么方法可以按照我想要的方式将参数传递给 getElementById 吗?
我尝试为identifier2输入一个硬编码值,该值确实有效,但意味着我无法按照我计划的方式使用该函数。我还尝试在字符串(
${identifier2}
)内使用identifier2,但这不起作用。
Nightmare 同时运行 Node.js 进程和浏览器进程。主要测试代码在 Node.js 进程中运行,但 Nightmare 会序列化您传递给
evaluate
的函数并在浏览器进程中运行它。所以你不能只是关闭变量。相反,将您需要的值作为后续参数传递到 evaluate
中,并更新函数签名以期望它们作为参数。这是文档中显示此内容的示例:
const selector = 'h1' nightmare .evaluate(selector => { // now we're executing inside the browser scope. return document.querySelector(selector).innerText }, selector) // <-- that's how you pass parameters from Node scope to browser scope .then(text => { // ... })
(这是他们的代码注释。请注意,“范围”这个词不太正确,但这是总体思路。)
调整您的代码来做到这一点:
async function checkPrice(url2, identifier2) {
console.log(identifier2)
const priceString = await nightmare.goto(url2)
.wait(`#${identifier2}`)
.evaluate((identifier2) => document.getElementById(identifier2).innerText, identifier2)
// ^^^^^^^^^^^ ^^^^^^^^^^^^^
.end()
console.log(priceString)
console.log("Hello!")
}