【问题标题】:Downloading a file with CasperJS from POST attachment从 POST 附件下载带有 CasperJS 的文件
【发布时间】:2015-11-24 20:43:09
【问题描述】:

我几乎可以完成这项工作,但当它出现时,我似乎无法下载该文件。我在这里做错了什么?单击“下载销售报告”按钮时,我的 console.log() 应该下载一个 CSV 文件,甚至永远不会触发。

var casper = require('casper').create();
casper.start('http://www.waynecountyauditor.org/Reports.aspx?ActiveTab=Sales')
.waitForText("Accept")
.thenClick('#ctl00_ContentPlaceHolder1_btnDisclaimerAccept')
.waitForText("View Sales")
.thenClick('#ctl00_ContentPlaceHolder1_WeeklySales_fvSalesReport_btnViewSales')
.waitForText("Download Sales Report")
.thenClick(x('//*[@id="ctl00_blSearchLinks"]/li[4]/a'))
.wait(1000)
.on('page.resource.received', function(resource) {
console.log('here');
if (resource.stage !== "end") {
    return;
}
if (resource.url.indexOf('results.csv') > -1) {
    this.download(resource.url, 'D:\Jobs\Currency\testing\ExportData.csv');
}

});
casper.run();

【问题讨论】:

  • 您是否尝试在最后一个thenClick 之前或在thenClick 回调中注册到“page.resource.received”?
  • 我猜你是这个意思?不,这也不起作用。 .thenClick(x('//*[@id="ctl00_blSearchLinks"]/li[4]/a'),function(){ casper.on('page.resource.received', function(resource) { console.log('here'); if (resource.stage !== "end") { return; } if (resource.url.indexOf('results.csv') > -1) { this.download(resource.url, 'D:\Jobs\Currency\testing\ExportData.csv'); } }); })
  • @Adam 我运行了您的脚本并注意到resource.url 不包含字符串“results.csv”,而是包含您下载页面的地址。所以最好这样做:` if (resource.contentType.indexOf('text/csv') > -1) { this.download(resource.url, './ExportData.csv'); } ` 但它也不起作用,因为要接收文件,您必须 POST 表单并且 casper.download 默认获取它。我试图调整this answer 以使用 POST 下载,但由于某种原因它不起作用:请求只会重新加载页面。正在进行的工作:pastebin.com/974wF4WR
  • 如果我们能从 CasperJS/PhantomJS 获得原始响应体就好了。
  • 感谢您调查 Vaviloff。我已经尝试适应几乎所有我能找到的答案,而且我一直在用头撞墙。希望我们能有所收获。

标签: phantomjs casperjs


【解决方案1】:

我终于明白了。瓦维洛夫有我需要的 99%。我只是错过了 2 个帖子变量。感谢您的帮助瓦维洛夫!

    // http://stackoverflow.com/questions/33903418/downloading-a-file-with-casperjs-from-post-attachment
    var casper = require('casper').create({
        verbose: true,
        logLevel: 'debug',
        pageSettings: {
              loadImages:  false         // The WebPage instance used by Casper will
            , loadPlugins: false         // use these settings
            ,  userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
        }
    });
    var x = require('casper').selectXPath;
    var utils = require('utils');

    casper.on('remote.message', function(message) {
        this.echo('LOG: ' + message);
    });

    casper.start()
    .open('http://clintonoh.ddti.net/Reports.aspx?ActiveTab=Sales')
    .waitForText("Accept")
    .thenClick('#ctl00_ContentPlaceHolder1_btnDisclaimerAccept')
    .waitForText("View Sales")
    .thenClick('#ctl00_ContentPlaceHolder1_WeeklySales_fvSalesReport_btnViewSales')
    .waitForText("Download Sales Report", function(){

        // Adapted from: http://stackoverflow.com/questions/16144252/downloading-a-file-that-comes-as-an-attachment-in-a-post-request-response-in-pha
        var res = this.evaluate(function() {

            document.getElementById('__EVENTTARGET').value='ctl00$blSearchLinks' /* Was missing these 2 */
            document.getElementById('__EVENTARGUMENT').value='4'

            var res={};
            f=document.getElementById("aspnetForm");
            var previous_onsubmit = f.onsubmit;
            f.onsubmit = function() {

                //previous_onsubmit();

                //iterate the form fields
                var post={};
                for(i=0; i<f.elements.length; i++) {
                   //console.log(f.elements[i].name + " = " + f.elements[i].value);
                   post[f.elements[i].name]=f.elements[i].value;
                }
                res.action = f.action;
                res.post = post;
                return false; //Stop form submission
            }

            // Trigger the click on the link.
            var link = document.evaluate('//*[@id="ctl00_blSearchLinks"]/li[5]/a', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
            try {

                var e = document.createEvent('MouseEvents');
                e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                link.dispatchEvent(e);

            } catch(error){
                console.log(error);
            }

            return res; //Return the form data to casper
        });

        //Start the download
        casper.download(res.action, "./ExportData.csv", "POST", res.post);    
        //casper.capture("./image.png");    

    })

    casper.run();

【讨论】:

    【解决方案2】:

    经过长时间的研发终于得到了答案,我们可以使用download节点模块下载附件如下

    const fs = require('fs');
    
    const download = require('download');
    
    download('http://unicorn.com/foo.pdf').then(data => {
        fs.writeFileSync('dist/foo.pdf', data);
    });`
    

    Link to Download NPM Module

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      相关资源
      最近更新 更多