在 Nightmare evaluate() 中使用时将参数传递给 document.getElementById

2024-02-21

我正在尝试运行我的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) to document.getElementById("price").innerText)然后就可以正常工作了。

有什么办法可以传递参数getElementById()以我想做的方式?

我尝试过输入硬编码值identifier2这确实有效,但意味着我无法按照我计划的方式使用该功能。我也尝试过使用identifier2字符串内部 (${identifier2})这不起作用。


Nightmare 同时运行 Node.js 进程和浏览器进程。主要测试代码在 Node.js 进程中运行,但 Nightmare 会序列化您传递给的函数evaluate并在浏览器进程中运行它。由于它们处于完全不同的进程中,因此您不能仅关闭变量。相反,将您需要的值传递到evaluate作为后续参数,并更新函数签名以期望它们作为参数。这是显示这一点的示例文档 https://github.com/segment-boneyard/nightmare#evaluatefn-arg1-arg2:

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!")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Nightmare evaluate() 中使用时将参数传递给 document.getElementById 的相关文章

随机推荐