gpt4 book ai didi

javascript - 使用 Electron (NightareJS) 重复单击页面上的元素

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

我正在为动态网页编写页面抓取工具。该页面进行初始加载,然后在短暂加载时间后加载其余内容。

我已经考虑了负载并成功地从页面中抓取了 HTML,但页面并未立即加载所有内容。相反,它通过 GET 请求 URL 加载指定数量的内容,然后在页面上有一个“获取更多”按钮。我的目标是单击“获取更多”按钮,直到所有内容都加载到页面上。对于那些想知道的人,我不希望通过 GET URL 一次加载所有内容,因为这会影响他们的服务器。

我陷入了形成循环或迭代的困境,这将允许我重复单击页面。

const NIGHTMARE = require("nightmare");		
const BETHESDA = NIGHTMARE({ show: true });

BETHESDA
// Open the bethesda web page. Web page will contain 20 mods to start.
.goto("https://bethesda.net/en/mods/skyrim?number_results=40&order=desc&page=1&platform=XB1&product=skyrim&sort=published&text=")

// Bethesda website serves all requested mods at once. Each mod has the class "tile". Wait for any tile class to appear, then proceed.
.wait(".tile");

let additionalModsPresent = true;
while(additionalModsPresent) {
setTimeout(function() {
BETHESDA
.wait('div[data-is="main-mods-pager"] > button')
.click('div[data-is="main-mods-pager"] > button')
}, 10000)


additionalModsPresent = false;
}


// let moreModsBtn = document.querySelector('div[data-is="main-mods-pager"] > button');

// .end()
BETHESDA.catch(function (error) {
console.error('Search failed:', error);
});

到目前为止,我的想法是使用 while 循环,尝试在一段时间间隔后单击按钮。如果出现错误,可能是因为该按钮不存在。我遇到的问题是我似乎无法在 setTimeout 或 setInterval 内进行点击。我相信存在某种范围界定问题,但我不知道到底发生了什么。

如果我能让 click 方法在 setInterval 或类似的方法中工作,问题就可以解决。

想法?

最佳答案

可以引用问题(循环中运行 Nightmare 的问题)[ https://github.com/segmentio/nightmare/issues/522]

我按照给定的指导方针修改了您的代码。看起来效果不错

const NIGHTMARE = require("nightmare");
const BETHESDA = NIGHTMARE({
show: true
});

BETHESDA
// Open the bethesda web page. Web page will contain 20 mods to start.
.goto("https://bethesda.net/en/mods/skyrim?number_results=40&order=desc&page=1&platform=XB1&product=skyrim&sort=published&text=")

// Bethesda website serves all requested mods at once. Each mod has the class "tile". Wait for any tile class to appear, then proceed.
.wait(".tile");

next();

function next() {
BETHESDA.wait('div[data-is="main-mods-pager"] > button')
.click('div[data-is="main-mods-pager"] > button')
.then(function() {
console.log("click done");
next();
})
.catch(function(err) {
console.log(err);
console.log("All done.");
});
}

最终,按钮的 wait() 应该超时,然后您可以在 catch() block 中处理错误。当心它会一直持续下去:)我没有等到最后(你可能会耗尽内存)。

关于javascript - 使用 Electron (NightareJS) 重复单击页面上的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44605473/

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