gpt4 book ai didi

javascript - Nightmarejs .click() 在每个元素上有延迟

转载 作者:行者123 更新时间:2023-11-29 10:08:15 24 4
gpt4 key购买 nike

我正在尝试使用 Nightmarejs 制作简单的跟随脚本。它应该以下一种方式工作:

  1. 转到一些用户个人资料
  2. 点击按钮打开该用户的关注者列表
  3. 点击所有关注按钮,每次点击之间有延迟
  4. 点击加载更多
  5. 重复第 3 步和第 4 步几次

到目前为止我所拥有的是这个,它没有错误,但它只点击了第一个跟随按钮,那就是结束:

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);
});

我试着循环点击像这样的关注按钮,但它给我错误 $ is not defined

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);
});

我相信对于有 Nightmarejs 经验的人来说,这将是一个简单的任务,但我才刚刚开始,现在已经为它苦苦挣扎了 2 天。

如果有任何帮助,我将不胜感激。

最佳答案

你得到 $ is not defined因为这种语法是 jQuery 的一部分,所以当您编写 NightmareJS 脚本时,它使用纯 javascript。

由于函数 .inject("js", "https://code.jquery.com/jquery-3.1.0.min.js"),您可以加载 jquery 库(在求值之前)

我们需要同步休眠,否则 NightmareJS 可能会结束函数 ̀ evaluate在它完成之前。 (我在这个线程上找到了 sleep 的代码:https://stackoverflow.com/a/17532524/6479780)如果你想尝试异步 sleep ,你必须使用 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);
});

关于javascript - Nightmarejs .click() 在每个元素上有延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38861369/

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