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

问题描述 投票:0回答:1

我正在尝试使用传入的参数运行我的

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}
,但不起作用。

javascript getelementbyid nightmare
1个回答
2
投票

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!")
}
© www.soinside.com 2019 - 2024. All rights reserved.