gpt4 book ai didi

javascript - 如何在浏览器范围内设置全局变量.wait(fn)NightmareJS

转载 作者:行者123 更新时间:2023-12-03 13:24:16 26 4
gpt4 key购买 nike

我想基于要抓取的网络设置全局变量。但是,我只能使用.evaluate和.then来做到这一点。这不是我所需要的,因为在那之后我什么也不能运行。

谢谢您的帮助! :)

var global;

nightmare
.goto(url)
.wait(() => {
global = document.getElementById("element").textContent;
})
.click()
.wait()
.more...

最佳答案

人们会告诉您不要对全局变量进行处理。我猜您只想在一些小的脚本中存储和使用一些数据。有几种保存变量供以后使用的方法。我现在不会通过数据库之类的东西。

Nightmare 实例中的窗口对象

您可以使用window对象,因为只要您位于同一页面并且不刷新页面,它就会在那里。

await nightmare
.goto(url)
.evaluate(() => {
window.aGlobalVariable = document.getElementById("element").textContent;
})

然后稍后,只要您在同一页面中,您就可以稍后再调用它。
await nightmare
.evaluate(() => {
console.log(`${aGlobalVariable} looks tasty`);
})

在上下文之间保存和传递变量
let aGlobalVariable;
aGlobalVariable = await nightmare
.goto(url)
.evaluate(() => {
return document.getElementById("element").textContent;
})

现在,您可以从nodeJS上下文访问aGlobalVariable。
只要您再次在nightmareJS中使用它,就可以再次将其传递给浏览器。
await nightmare
.goto(url)
.evaluate((aGlobalVariable) => { // <-- call it in the function
console.log(`${aGlobalVariable} looks tasty.`)
}, aGlobalVariable) // <-- pass it here

确保您了解异步等待和 promise ,否则运行这些代码时最终会收到奇怪的错误。

这里有一些引用。
  • https://ponyfoo.com/articles/understanding-javascript-async-await
  • 关于javascript - 如何在浏览器范围内设置全局变量.wait(fn)NightmareJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46962783/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com