mike yaworski mike yaworski - 7 months ago 135
HTML Question

CasperJS - How to open up all links in an array of links

I'm trying to make it so that CasperJS will open up every link in an

array
of links. I have it so that after I open a link, it will display the title of that page. Yet when I run it, nothing is displayed.

I can use a
for loop
to display the links and it works perfectly.

This is the code for what I just explained:

var x;

casper.start(URL, function() {

x = links.split(" "); // now x is an array of links

for (var i = 0; j < x.length; i++) // for every link...
{
casper.thenOpen(partialURL + x[i], function() { // open that link
console.log(this.getTitle() + '\n'); // display the title of page
});
}

this.exit();
});

casper.run();


This is another method I tried:

var x;

casper.start(URL, function() {
x = links.split(" "); // now x is an array of links
this.exit();
});

for (var i = 0; j < x.length; i++) // for every link...
{
casper.thenOpen(partialURL + x[i], function() { // open that link
console.log(this.getTitle() + '\n'); // display the title of page
});
}

casper.run();


It says that 'x' in undefined. Notice that I set x to be a global variable though.
Any modifications that you could make would be great. Thanks.

Answer
var x; var i = -1;

casper.start(URL, function() {
    x = links.split(" "); // now x is an array of links
});

casper.then(function() {
    this.each(x, function() { 
        i++; // change the link being opened (has to be here specifically)
        this.thenOpen((partialURL + x[i]), function() {
            this.echo(this.getTitle()); // display the title of page
        });
    });
});

casper.run();