gpt4 book ai didi

javascript - Nightmare.js - addEventListener 单击函数不会执行

转载 作者:行者123 更新时间:2023-11-28 05:38:27 26 4
gpt4 key购买 nike

我正在尝试弄清楚如何使脚本单击链接并转到某个页面,然后执行某些操作。这是我坚持的例子,它不起作用。

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare

.goto("https://www.google.com/")
.type("input", "nightmare.js")
.wait(3000)
.click("button[type=submit]")
.wait(2000)
.evaluate(function(){
var title = document.querySelectorAll("h3 a");
i = 0;

if (title) {
title[i].addEventListener("click", function(){
setTimeout(function(){
alert("Success!");
}, 5000);
});
}
})

.then(function(result){
console.log("result", result);
})
.catch(function (error) {
console.error('Search failed:', error);
});

如您所见,它甚至不会转到下一页。

但是如果我像这样定义点击,它将转到下一页,但我也需要它在另一个页面上执行某些功能:

.evaluate(function(){
var title = document.querySelectorAll("h3 a");
i = 0;

if (title) {
title[i].click();
}
})

所以这让我很困惑,不知道为什么它不起作用。

最佳答案

好吧,我认为主要问题在于您如何尝试单击该链接。现在,您在 Nightmare 链回调的主流程之外执行此操作(.goto().type().wait() ...链)。如果您更改流程以与链一起使用,并使用 .click()再次代替 .evaluate() ,您可以在下一页上执行操作:

nightmare
.goto("https://www.google.com/")
.type("input", "nightmare.js")
.wait(3000)
.click("button[type=submit]")
.wait("h3[class=r]")
.click("h3[class=r] a")
.evaluate(function(){
return document.querySelector("h1 a").innerHTML
})
.end()
.then(function(result){
console.log("result", result);
})
.catch(function (error) {
console.error('Search failed:', error);
});

这会输出带有 Nightmare 页面<h1></h1>链接的内容。标签是“Nightmare ”

关于javascript - Nightmare.js - addEventListener 单击函数不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39154224/

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