【发布时间】:2015-12-08 12:50:31
【问题描述】:
目前我用 Phantomjs 编写了一个脚本,它可以浏览多个页面。我的脚本有效,但我不知道如何设置刮擦之间的时间间隔。我尝试使用 setInterval 并大约每 5 秒从 arrayList 传递项目,但它似乎不起作用。我的脚本不断中断。这是我的示例 phantomjs 脚本代码:
没有setInterval
var arrayList = ['string1', 'string2', 'string3'....]
arrayList.forEach(function(eachItem) {
var webAddress = "http://www.example.com/eachItem"
phantom.create(function(ph) {
return ph.createPage(function(page) {
return page.open(yelpAddress, function(status) {
console.log("opened site? ", status);
page.injectJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
setTimeout(function() {
return page.evaluate(function() {
//code here for gathering data
}, function(result) {
return result
ph.exit();
});
}, 5000);
});
});
});
});
与setInterval:
var arrayList = ['string1', 'string2', 'string3'....]
var i = 0
var scrapeInterval = setInterval(function() {
var webAddress = "http://www.example.com/arrayList[i]"
phantom.create(function(ph) {
return ph.createPage(function(page) {
return page.open(yelpAddress, function(status) {
console.log("opened site? ", status);
page.injectJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
setTimeout(function() {
return page.evaluate(function() {
//code here for gathering data
}, function(result) {
return result
ph.exit();
});
}, 5000);
});
});
});
i++
if(i > arrayList.length) {
clearInterval(scrapeInterval);
}, 5000);
基本上,我想在arrayList 内发送一大块项目(其中 10-20 个),然后等待 1 - 2 分钟,然后再发送下一批项目,而不会使网站不堪重负。或者,如果有办法设置时间间隔以每 2-3 秒循环遍历数组中的每个项目。
【问题讨论】:
标签: javascript node.js web-scraping phantomjs iteration