gpt4 book ai didi

javascript - 模块化 Nightmare 并传递 Nightmare 实例

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

我试图从网站中提取数据,我想在 10 分钟后循环查看数据是否已更改。我认为将我的功能打包在模块中是一个好主意,但现在我坚持将我当前的 Nightmare 实例从登录模块转移到数据模块。

开始.js

var config = require('./config.json');
var login = require('./functions/login.js');
var data = require('./functions/data.js');
var vo = require('vo');

var Nightmare = require('nightmare'),
nightmare = new Nightmare({
show: config.nightmare.show,
typeInterval: config.nightmare.typeInterval,
webPreferences: {
images: config.nightmare.images,
}
});

vo(login.login)(nightmare, function (err, result) {
if (!result) return;
console.log('Logged in as ' + config.user.username)
vo(data.getData)(nightmare, function (err, result) {
console.log(result);
})
})

登录.js
var config = require('../config.json');
var Nightmare = require('nightmare')

function* login(nightmare) {
return yield nightmare
.goto('http://example.com/')
.click('.gogo').wait(2500)
.insert('.whsOnd', config.user.username)
.click('.RveJvd').wait(2500)
.insert('.whsOnd', config.user.password)
.click('.RveJvd').wait(4000)
.then(() => {
return true;
})
}
//login works

module.exports = {
login: login
}

数据.js
var config = require('../config.json');
var Nightmare = require('nightmare')

function* getData(nightmare) {
console.log('Getting data ...' + nightmare)
return yield nightmare
.click('.index_menu').wait(1000)
.evaluate(()=>{
// do stuff
})
.then((result) => {
return result;
})
.catch((error) => {
console.log('Failure: ' + error)
})
}

module.exports = {
getData: getData
}

我的评估函数正在工作,唯一的问题是,即使在 data.js 中没有定义 Nightmare ,例如路径是。

最佳答案

您创建了单独的 Nightmare 实例。它们不共享相同的 cookie session ,因此您的登录 session 不会反射(reflect)在 getdata 实例中。您可以尝试从登录实例传递 cookie 并将其设置在 getdata 实例中。

登录.js

         nightmare
.goto('http://example.com/')
.click('.gogo').wait(2500)
.insert('.whsOnd', config.user.username)
.click('.RveJvd').wait(2500)
.insert('.whsOnd', config.user.password)
.click('.RveJvd').wait(4000)
.cookies.get()
.then((cookie) => {
return cookie; // pass this cookie to getdata
})

数据.js
nightmare 
.cookies.set(cookies) //set cookies from login session
.click('.index_menu').wait(1000)
.evaluate(()=>{
// do stuff
})
.then((result) => {
return result;
})
.catch((error) => {
console.log('Failure: ' + error)
})
}

关于javascript - 模块化 Nightmare 并传递 Nightmare 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904685/

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