How to download a file through a custom POST request with CasperJS

后端 未结 1 1612
星月不相逢
星月不相逢 2021-01-25 08:40

I am writing a crawler and needs to download file generated after a form request using POST.

I have successfully used this.download(url,\'POST\',Params) for regular form

1条回答
  •  孤独总比滥情好
    2021-01-25 09:15

    casper.download() happily accepts a serialized form instead of an object, so you can still use it. You just have to serialize the form in the page context beforehand:

    var formData = casper.evaluate(function(){
      return $('form#theirForm').serialize();
    });
    
    var url;
    casper.download(url, targetFile, 'POST', params);
    

    The only problem might be, that another mimeType is used: "text/plain; charset=x-user-defined".

    In that case, you will have to recreate the whole cascade of functions that go into casper.download():

    var url;
    var response = casper.evaluate(function(url){
        var params = $('form#theirForm').serialize();
        var data = __utils__.sendAJAX(url, 'POST', params, false);
        return __utils__.encode(data);
    }, url);
    
    var cu = require('clientutils');
    
    fs.write("test.zip", cu.decode(response), 'wb');
    

    "application/x-www-form-urlencoded" is used by default for __utils__.sendAJAX().

    0 讨论(0)
提交回复
热议问题