user3064931
user3064931

Reputation: 129

Why the casperjs download() function doesn't work?

Why download() doesn't work in my script?

It fails the download and show no error even with verbose.

var casper = require('casper').create({
    verbose: true,
    logLevel: "debug",
    pageSettings: {
        webSecurityEnabled: false
    }
});

casper.start('https://developer.android.com/sdk/index.html', function() {

    var url = this.evaluate(function() {
        var selector = '#win-tools';
        return __utils__.findOne(selector).getAttribute('href');
    });

    this.download(url, 'apps/android-sdk.exe');

});

casper.run();

It should work, I don't understand.

Upvotes: 1

Views: 3284

Answers (2)

simonemainardi
simonemainardi

Reputation: 515

I was experiencing troubles too when using the built-in casper.download() function.

Specifically, casper.download() seems to randomly fail to write retrieved contents to disk. I have experienced this when trying to download an XML file sent as an attachment (Content-Disposition:attachment)

This could be related to the issue: https://github.com/n1k0/casperjs/issues/255

Following is my workaroud. I changed

casper.download(downlUrl, downlFileName);

To:

fs.write(downlFileName, this.base64encode(downlUrl)), 'w');

Now you will end up in having a base64-encoded file saved on the file system. You can easily convert it back to its format using a tool such as bash base64 (http://linux.die.net/man/1/base64).

Upvotes: 4

Christopher Ellis
Christopher Ellis

Reputation: 1116

Make sure you set a userAgent. I also used Javascript in the evaluate instead of the __utils__. I tested and this works:

var casper = require("casper").create ({
  waitTimeout: 5000,
  stepTimeout: 5000,
  verbose: true,
  viewportSize: {
    width: 1400,
    height: 768
  },
  pageSettings: {
    webSecurityEnabled: false
  },
  onWaitTimeout: function() {
        this.echo('** Wait-TimeOut **');
  },
  onStepTimeout: function() {
        this.echo('** Step-TimeOut **');
  }
});

casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4');

casper.start('https://developer.android.com/sdk/index.html');

casper.then(function() {
    var url = this.evaluate(function() {
        var selector = document.getElementById('win-tools');
            return selector.getAttribute('href');
    });
    this.echo('URL: ' + url);
    this.download(url, 'apps/android-sdk.exe');
});

casper.run(function() {
  this.echo('Done.').exit();
});

Upvotes: 1

Related Questions