javascript - 有没有办法等到新页面加载后再执行 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()
功能在用户单击按钮后等待。像这样:
<a href='newpage.html'><button id='click'>Click!</button</a>
$('#click').click(function() {
setTimeout(function() {
// code you want executed after page is loaded
}, 100);
});
推荐阅读
- asp.net-mvc - 如何在 MVC 中的回发中保留 formcollection 值
- java - Spark with Hive:找不到表或视图
- iframe - 嵌入包含导入的非公开日历的 Google 日历
- ios - 滑动 UIView 时出现动画错误
- spring-boot - 在同一个 schema.sql H2 中创建两个表
- amazon-web-services - 允许流量到 AWS WAF 中的特定路径
- ios - 缺少配置文件:应用程序必须在名为 embedded.mobileprovision 的文件中包含配置文件
- c# - botframework v4 - 使用最新的 Nuget 包
- android - 从现有的导入项目更改包路径
- postgresql - 跟踪 Postgres 中一行的最后修改时间戳