casperjs download file without specifying url

烂漫一生 提交于 2019-11-26 22:25:46

问题


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 download button. So, I may not be able to use download() well under the situation.


回答1:


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');
    }
});



回答2:


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.




回答3:


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




回答4:


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);


来源:https://stackoverflow.com/questions/12461096/casperjs-download-file-without-specifying-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!