Reputation: 1171
I'm working on a little project with CasperJS. The main idea is to get a links to pictures with title and description from subpages of some website. I already tried many different ways to achieve what I want, but I'm stuck with some piece of code and I don't want to continue with a possibly uncorrect way of coding.
This is current sequence of events in my code:
casper.start(url);
casper.thenEvaluate(openPicturesSubpage);
casper.then(getPicturesInfo);
casper.then(getPictureFullRes);
casper.run();
First two commands are working as expected, so I will skip to the structure of third function. The code of function (I'm using jQuery, because I need to get some specific stuff in other function) getPicturesInfo
(variable pictures
is global):
getPicturesInfo = function() {
pictures = this.evaluate(function() {
var array = [];
$('.picture-box a').each(function() {
arr.push({
'name': $(this).text(),
'subpage': $(this).attr('href')
});
});
return array;
});
}
Basically I have everything I need to continue "browsing" for actual full resolution links of pictures. So the next step is to append new data to already created array. This is also the main problem I want to solve. How to correctly iterate through array of previously saved data? So there's the code of the last function getPictureFullRes
:
getPictureFullRes = function() {
for (var i = 0; i < pictures.length; i++) {
this.thenOpen(pictures[i]['subpage'], getFullResLink);
}
}
The problem there is that I can't pass counter variable i
to my function getFullResLink
. I also tried to add another argument to thisOpen
method and argument to getFullResLink
function, but it doesn't work, because method don't have that functionality.
How could I access appropriate index of array inside getFullResLink
?
Upvotes: 1
Views: 225
Reputation: 61922
I see two possible ways to solve this.
Define a getFullResLinkWrapper
like this:
function getFullResLinkWrapper(pictureIndex){
return function(){
// contents of getFullResLink that uses `pictureIndex`
};
}
You can then call it like this:
this.thenOpen(pictures[i]['subpage'], getFullResLinkWrapper(i));
This way you can enclose the index variable for each iteration of getFullResLink
.
It is guaranteed that then()
steps are not skipped during the execution of CasperJS. So you can easily advance the counter inside of the getFullResLink
function:
function getFullResLink(){
if (pictureIndex == null) {
pictureIndex = 0;
} else {
pictureIndex++;
}
...
}
Upvotes: 2