关于范围:将CasperJS与PhantomJS Web服务器一起使用

Using CasperJS with PhantomJS webserver

我有一个Casper脚本,用于提交表单并抓取响应。

我试图建立一个"按需抓取"环境,在这里我可以使用PhatomJS网络服务器将表单值发布到url,然后在我的Casper脚本中使用该数据来刮取页面,然后在该页面上打印出响应。我看不到如何将post变量传递给casper,然后将响应传递回Phantom。

这里是我的基本幻影/卡斯普结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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中访问变量,然后在我完成抓取之后将数据传递回去?


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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//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+'/');