![](/img/trans.png)
[英]Javascript: best way to wait for script loaded synchonously before executing function?
[英]Is there a way to wait till a new page is loaded before executing another function in JavaScript?
我花了很多时间思考这个问题,现在尝试了不同的事情。 我想抓取一个包含多个页面的网页,但页面不会在页面更改时重新加载。 相反,在每个更改的页面上都会更改一些容器数据。 最困难的事情是知道何时单击下一页按钮。
有人可能会认为这很容易,我也是这么想的,然后开始做:
$('.pagn a').each(function() {
console.log(`Loop counter`)
$(this).click()
//Code to scrape the new page
})
现在,循环运行了 13 次,但只更改了一页。 这是因为分页本身位于重新加载的容器内,因此所有其他按钮按下基本上都被忽略了。
为了解决这个问题,我需要进行某种检查,以确保在继续之前已加载新内容,但如果我尝试执行以下操作:
$('.pagn a').each(function() {
console.log(`Loop counter`)
while (someConditionToCheckIfPageLoaded) {
}
$(this).click()
//Code to scrape the new page
})
这将是一个无限循环,因为 JavaScript 是单线程的,并且更改条件的代码永远不会触发。
我也试过这个,我现在知道这是不正确的。
正在加载页面的指示器是按钮 URL 是否与页面 URL 匹配。
$('.pagn a').each(function() {
let visitedURL = [];
if ($(this).attr('data-url')) {
let button = $(this)
buttonURL = "https://www.ebay.com/myb/PurchaseHistory#" + $(this).attr('data-url');
(function wait() {
button.click()
if (buttonURL == location.href && !visitedURL.includes(button.html())) {
console.log(button.html())
button.click()
visitedURL.push(button.html())
console.log(buttonURL);
console.log(location.href);
//Scrape page
} else {
setInterval(wait, 5000);
}
})();
}
})
这也只会更改一页。
如果有人能够使用 JavaScript 抓取具有多个页面的网页,请告诉我如何。
编辑1:
另外,我不确定为什么这也会创建一个无限循环:
let glbElements = []
$('.pagn a').each(function() {
glbElements.push($(this))
})
for(let i = 0 ; i<glbElements.length; i++){
console.log(`Loop Counter`)
setTimeout(function(){
console.log(`Inside SetTimeout`)
glbElements[i].click()
glbElements.splice(i,1)
},2000)
}
Lopp Counter *5 Inside SetInterval -- 保持打印
您可以使用setTimeout()
function 在用户单击按钮后等待。 像这样:
<a href='newpage.html'><button id='click'>Click!</button</a>
$('#click').click(function() {
setTimeout(function() {
// code you want executed after page is loaded
}, 100);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.