2012-09-17 55 views
3

有沒有什麼辦法可以用casperjs下載CSV文件而不指定下載URL?我正在嘗試下載CSV文件,該文件的URL是在單擊下載按鈕時動態生成的。所以,我可能無法在這種情況下使用download()。casperjs下載文件時不指定url

回答

2

根據記錄,它使用「resource.received」事件是已經成爲可能。 如果您收到這樣的標題:

Content-Disposition:Attachment;文件名=「ExportData.csv」

產生可以用下面的事件監聽器下載文件:

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

@DiegoBorges我不記得是哪個版本。但是我發現CASPER-1.1.0-DEV有這個功能:http://docs.casperjs.org/en/latest/events-filters.html –

1

我已經找到了一個解決方案。它不是很乾淨,但它的工作原理:

您需要構建一個全局數組,它將每個resource.received關聯一個文件名。

fileInfos[url]= parse_filename_from_responseHeader(resource) 

如果url是您想要下載的資源,請先嚐試打開(url)。這將觸發resiyrce.received事件,解析頭並更新全局數組。

現在,在啓動casper.download(url)之前,請查找fileInfos[url]

您會在fileInfos數組中找到與url對應的文件名。 如果需要,我可以詳細說明解決方案,但是由於問題已經過了幾年,所以我會等待下一步的闡述。

0

我會做的就是這樣的事情,但我知道我要去的文件名獲得:

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