Pla*_*kac 4 javascript jquery browser-automation phantomjs nightmare
我正在尝试使用 Nightmarejs 制作简单的跟随脚本。它应该以下一种方式工作:
到目前为止我所拥有的是这个,它没有错误,但它只点击第一个关注按钮,那就是结束:
var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true })
nightmare
.goto('http://example.com/')
.click('.buttonOpenModal')
.wait(4000)
.click('.buttonFollow')
.end()
.then(function (result) {
console.log(result)
})
.catch(function (error) {
console.error('Search failed:', error);
});
Run Code Online (Sandbox Code Playgroud)
我试图循环点击这样的关注按钮,但它给了我错误$ 未定义
var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true })
nightmare
.goto('http://example.com/')
.click('.buttonOpenModal')
.wait(4000)
.evaluate(function(){
$('.buttonFollow').each(function() {
$(this).click();
});
})
.end()
.then(function (result) {
console.log(result)
})
.catch(function (error) {
console.error('Search failed:', error);
});
Run Code Online (Sandbox Code Playgroud)
我相信对于在 Nightmarejs 中有经验的人来说,这将是一项简单的任务,但我才刚刚开始,并且已经为此苦苦挣扎了 2 天。
我真的很感激任何帮助。
小智 5
你得到$ is not defined,因为这个语法的jQuery的一部分,当你写NightmareJS脚本,它使用纯JavaScript。
由于功能,您可以加载 jquery 库(在评估之前) .inject("js", "https://code.jquery.com/jquery-3.1.0.min.js")
我们需要同步睡眠,否则 NightmareJS 可能会结束函数?evaluate在它完成之前。(我sleep在这个线程上找到了代码:https : //stackoverflow.com/a/17532524/6479780)如果你想尝试异步睡眠,你必须使用setTimeout(callback, millis)
这里是我会做的,使用纯javascript:
var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true })
nightmare
.goto('http://example.com/')
.click('.buttonOpenModal')
.wait(4000)
.evaluate(function(){
function sleep(ms) {
var start = new Date().getTime(), expire = start + ms;
while (new Date().getTime() < expire) { }
return;
}
var list = document.querySelectorAll('.buttonFollow');
list.forEach(function(elt){
elt.click();
//We need synchronous sleep here
sleep(2000); //Wait 2 seconds
});
})
.end()
.then(function (result) {
console.log(result)
})
.catch(function (error) {
console.error('Search failed:', error);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4337 次 |
| 最近记录: |