casperjs download file without specifying url

后端 未结 4 500
[愿得一人]
[愿得一人] 2020-12-04 00:04

Is there any way to download CSV file with casperjs without specifying download URL? I am trying to download CSV file whose URL is dynamically generated when I click the dow

相关标签:
4条回答
  • 2020-12-04 00:34

    For the record, it's already possible using 'resource.received' event. If you receive header like this one:

    Content-Disposition: Attachment; Filename="ExportData.csv"

    The file generated can be downloaded using following event listener:

    casper.on('resource.received', function(resource) {
        if (resource.stage !== "end") {
            console.log("resource.stage !== 'end'");
            return;
        }
        if (resource.url.indexOf('ExportData.csv') > -1) {
            console.log("Downloading csv file");
            this.download(resource.url, 'ExportData.csv');
        }
    });
    
    0 讨论(0)
  • 2020-12-04 00:40

    This won't be possible until this phantomjs issue will be solved http://code.google.com/p/phantomjs/issues/detail?id=52

    0 讨论(0)
  • 2020-12-04 00:44

    What I would do is something like this but I know the filename that I am gonna receive:

    this.waitForResource(function check(resource){
                res = resource;    
                // regular expression to test
                return /thefilename/.test(resource.url);
            }, function(){
                this.echo("Resource found: " + res.url);
                // download the file
                this.download(res.url, path);
            }, null, 10000);
    
    0 讨论(0)
  • 2020-12-04 00:55

    I have found a solution for that. It is not very clean but it works :

    You need to build an global array, which associates every resource.received having a filename attached.

    fileInfos[url]= parse_filename_from_responseHeader(resource)
    

    If url is the resource you want to download, try open(url) first. This will trigger the resiyrce.received event, parse the header and update the global array.

    Now, before launching the casper.download(url), look for fileInfos[url].

    You will find the filename corresponding to the url in the fileInfos array. I can elaborate on the solution if needed, but since the question is already a few years old,

    I'll wait for the next poke to elaborate.

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