Costa Rassco
Costa Rassco

Reputation: 169

how to save files in "while" with phantomjs?

I need to save 4 files in html output.

here is the code in phantomjs:

var i = 0;

while (i<4)
{
var page = require('webpage').create();

var fs = {};
fs = require('fs');

if(i==0)
{
    var url = 'http://www.lamoda.ru/shoes/dutiki-i-lunohody/?sitelink=leftmenu&sf=16&rdr565=1#sf=16';

} else {
    var url = 'http://www.lamoda.ru/shoes/dutiki-i-lunohody/?sitelink=leftmenu&sf=16&rdr565=1#sf=16&p='+i;
}


page.open(url, function (status) {
    var js = page.evaluate(function () {
        return document;
    });
    console.log(js.all[0].outerHTML); 

    page.render('export'+i+'.png');

    fs.write(i+'.html', js.all[0].outerHTML, 'w');

    phantom.exit();
});

i++;
}

It seems that I need to change the FS variable, but I don't know how... I don't need create fs1,fs2,fs3,fs4... I need to find you the better solution, hope you will help, thank you)

Upvotes: 1

Views: 184

Answers (1)

Darren Cook
Darren Cook

Reputation: 28938

Is it okay if your requests are serial, so page 2 is not requested until page 1 has returned? If so I recommend you base your code of this multi-url sample in the documentation.

If you want the requests to run in parallel then you need to use a JavaScript closure to protect the local variables (see https://stackoverflow.com/a/17619716/841830 for an example of how to do that). Once you are doing that you can then either parse "url" to find out if it ends in p=1, p=2, etc. Or assign i inside the page object, and access it with this.i.

Upvotes: 1

Related Questions