vum*_*sha 16 phantomjs casperjs
我想下载一个CSV文件,它是通过POST请求点击按钮生成的.我在casperJs和phantomJS论坛上进行了最好的研究并空手而归.在像firefox这样的普通浏览器中,在发布请求后会出现浏览器下载对话窗口.如何在PhantomJS中处理这种情况
TTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
Content-disposition: attachment;filename=ExportData.csv
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Fri, 19 Apr 2013 23:26:40 GMT
Content-Length: 65183
Run Code Online (Sandbox Code Playgroud)
我找到了一种方法来使用casperjs(如果你使用XMLHttpRequest实现下载功能,它应该单独使用phantomjs,但我没有尝试过).
我将给你留下一个工作实例,试图从这个页面下载最近的PDF文件.当您单击下载链接时,会触发一些javascript代码,生成一些隐藏的输入字段,然后进行POST.
我们所做的是替换表单的onsubmit函数,以便取消提交,并获取表单目标(操作)及其所有字段.我们稍后会使用此信息进行实际下载.
var casper=require('casper').create();
casper.start("https://sede.gobcan.es/tributos/jsf/publico/notificaciones/comparecencia/ultimosanuncios.jsp", function() {
var theFormRequest = this.page.evaluate(function() {
var request = {};
var formDom = document.forms["resultadoUltimasNotif"];
formDom.onsubmit = function() {
//iterate the form fields
var data = {};
for(var i = 0; i < formDom.elements.length; i++) {
data[formDom.elements[i].name] = formDom.elements[i].value;
}
request.action = formDom.action;
request.data = data;
return false; //Stop form submission
}
//Trigger the click on the link.
var link = $("table.listado tbody tr:first a");
link.click();
return request; //Return the form data to casper
});
//Start the download
casper.download(theFormRequest.action, "downloaded_file.pdf", "POST", theFormRequest.data);
});
casper.run();
Run Code Online (Sandbox Code Playgroud)
注意:您必须使用--ignore-ssl-errors运行它,因为它们使用的CA不在您的浏览器默认CA列表中.
casperjs --ignore-ssl-errors=true downloadscript.js
Run Code Online (Sandbox Code Playgroud)