【问题标题】:Using CasperJS with PhantomJS webserver将 CasperJS 与 PhantomJS 网络服务器一起使用
【发布时间】:2013-12-15 22:46:13
【问题描述】:

我有一个 casper 脚本,可以提交表单并抓取响应。

我正在尝试设置一个“按需抓取”环境,在该环境中我可以使用 PhatomJS 网络服务器将表单值发布到 url,然后在我的 Casper 脚本中使用该数据来抓取页面,然后在网页上打印出响应.我不知道如何将 post 变量传递给 casper,然后将响应传递回 Phantom。

这是我的基本 Phantom/Casper 结构:

var server = require('webserver').create();

server.listen(8080, function(request, response) {

phantom.casperPath = '/source/casper/casperjs';
phantom.injectJs('/source/casper/casperjs/bin/bootstrap.js');

var address = request.post.address;

var casper = require('casper').create();

    casper.start();

casper.then(function(){
        address = // want to access global address here
    result = begin(this, address);  //Contians Casper scrape code
});

casper.run(function(){
        this.exit();
});

response.statusCode = 200;
response.write(result);  // from casper
    response.close();
});

有什么方法可以在 casper 中从 phantom 访问变量,然后在我完成抓取后将数据传回?

【问题讨论】:

    标签: scope web-scraping phantomjs casperjs


    【解决方案1】:

    除非您在 PhantomJS 中做一些在 CasperJS 中无法完成的事情,否则您最好在 CasperJS 中启动服务器并在那里响应您的 Casper 函数的结果。

    基于:https://stackoverflow.com/a/16489950/1096083

    //includes web server modules
    var server = require('webserver').create();
    
    
    //start web server
    var service = server.listen(ip_server, function(request, response) {
    
        var results;
    
        var address = request.post.address; // this is not working the way you would expect, needs a little help
        var casper = require('casper').create();
    
         casper.start(address, function() {
            // do some stuff with casper
            // store it in results
         });
    
         casper.then(function() {
            // do some more stuff with casper
            // store that in results too
         });
    
         casper.run(function() {
            response.statusCode = 200;
            response.write(results);
            response.close();              
         });
    
    });
    
    console.log('Server running at http://localhost:' + ip_server+'/');
    

    【讨论】:

    • 该页面上的答案下方有一条评论,该评论引发了此方法的内存问题。你有过这种经历吗?
    • 我使用它的项目从未真正通过实验阶段 - 所以我无法验证它。
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多