如何在node.js中使用CasperJS?

时间:2012-02-27 01:43:30

标签: node.js phantomjs

我想在node.js中使用CasperJS。

我已经引用了以下URL来在node.js中使用CasperJS:

在上述URL的帮助下,我编写了以下代码:

//DISPLAY=:0 node test2.js
var phantom = require('phantom');
console.log('Hello, world!');
phantom.create(function (ph) {
    ph.casperPath = '/opt/libs/casperjs'
    ph.injectJs('/opt/libs/casperjs/bin/bootstrap.js');
    var casper = require('casper').create();
    casper.start('http://google.fr/');

    casper.thenEvaluate(function (term) {
        document.querySelector('input[name="q"]').setAttribute('value', term);
        document.querySelector('form[name="f"]').submit();
    }, {
        term: 'CasperJS'
    });

    casper.then(function () {
        // Click on 1st result link
        this.click('h3.r a');
    });

    casper.then(function () {
        console.log('clicked ok, new location is ' + this.getCurrentUrl());
    });

    casper.run();
});

当我运行此代码时,出现以下错误:

ERROR MSG:

tz@tz-ubuntu:/opt/workspaces/TestPhantomjs$ DISPLAY=:0 node test2.js 
Hello, world!
Error: Cannot find module 'casper'
    at Function._resolveFilename (module.js:332:11)
    at Function._load (module.js:279:25)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at /opt/workspaces/TestPhantomjs/test2.js:6:14
    at Object.<anonymous> (/opt/workspaces/TestPhantomjs/node_modules/phantom/phantom.js:82:43)
    at EventEmitter.<anonymous> (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode/index.js:215:30)
    at EventEmitter.emit (events.js:67:17)
    at handleMethods (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode-protocol/index.js:138:14)
    at EventEmitter.handle (/opt/workspaces/TestPhantomjs/node_modules/phantom/node_modules/dnode-protocol/index.js:98:13)
phantom stdout: Unable to load casper environment: Error: Failed to resolve module fs, tried fs

6 个答案:

答案 0 :(得分:25)

您可以使用SpookyJS从Node驱动CasperJS。

答案 1 :(得分:21)

https://groups.google.com/group/casperjs/browse_thread/thread/641e9e6dff50fb0a/e67aaef5ab4ec918?hl=zh-CN#e67aaef5ab4ec918

Nicolas Perriault
2012/2/27天猪蓝虫。 :

  

我想在nodejs中使用casperjs。   并参考:   https://github.com/sgentle/phantomjs-node和   http://casperjs.org/index.html#faq-executable

     

你无法以这种方式运行CasperJS; QtWebKit和V8不共享相同的内容   js环境(和事件循环),所以你的node.js应用程序将无法   加载并使用CasperJS模块。您必须运行CasperJS脚本   分别使用子进程调用like this one on github。一世   不打算让CasperJS与phantomjs-node兼容,因为它   使用基于alert()的肮脏黑客我并不容易。

     

干杯,    - Nicolas Perriault

答案 2 :(得分:17)

CasperJS includes a web server to talk to the outside world。节点(使用requestsuperagent等)现在可以通过HTTP与casper通信。

scraper.js

#!/usr/bin/env casperjs

// I AM NOT NODEJS
// I AM CASPER JS
// I RUN IN QTWEBKIT, NOT V8

var casper = require('casper').create();
var server = require('webserver').create();
var ipAndPort = '127.0.0.1:8585';

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

    casper.start('https://connect.data.com/login');
    casper.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
    casper.then(function(){
        // lots of code here, and a few more cassper.then()s
    });

    casper.run(function(){
        console.log('\n\nFinished')
        response.statusCode = 200;
        var body = JSON.stringify({
            phoneNumber: '1800-YOLO-SWAG'
        })

        response.write(body);
        response.close();
    });
});

您现在可以将scraper.js作为网络服务器运行:

chmod +x scraper.js
./scraper.js

你应该run it as a Linux service just like you would for a node app

答案 3 :(得分:3)

一个解决方案(对我有用)是在每个测试的基础上启动和停止服务器。例如,我有runtests.coffee看起来像:

http = require 'http'
glob = require 'glob'
spawn = require('child_process').spawn

db = require './db' # Contains all database stuff.
webapp = require './webapp' # Contains all of the Express stuff.

db.connect 'test' # Connects to the db server and creates an empty test db.
server = http.createServer webapp.makeApp()
server.listen 0, ->
    port = server.address().port
    process.env.URL = "http://localhost:#{ port }"
    glob 'tests/*', (err, filenames) ->
        child = spawn 'casperjs', ['test'].concat(filenames)
        child.stdout.on 'data', (msg) -> process.stdout.write msg
        child.stderr.on 'data', (msg) -> process.stderr.write msg
        child.on 'exit', (code) ->
            db.disconnect() # Drops the test db.
            server.close()
            process.exit code

我在tests/中的CasperJS测试看起来像是:

URL = require('system').env.URL # Note, Casper code here, not Node.

casper.test.begin 'Test something', 1, (test) ->
    casper.start "#{ URL }/welcome"
    casper.then ->
        test.assertHttpStatus 200
        # ....
    casper.run ->
        test.done()

答案 4 :(得分:0)

它基本上意味着你的脚本找不到Casper;你检查了路径并确保

/opt/libs/casperjs 

/opt/libs/casperjs/bin/bootstrap.js

网站用户可以访问吗?考虑到它的位置可能不太可能。 / opt是一个unix路径,但该网站将在{websiterootpath} / opt。

中查找

我会在您网站的根文件夹中创建一个子文件夹'casperjs'并复制

的内容
/opt/libs/casperjs 
到那儿。 然后从

更改路径
/opt/libs/casperjs

/casperjs

答案 5 :(得分:0)

我也尝试通过节点cron作业运行casper, 这是我的解决方法

在casper.js中回显您的响应:

casper.then(function() {
    var comments = this.evaluate(getComments);
    this.echo(JSON.stringify(comments));
})

在节点文件casper_wrapper.js中使用node-cmd:

var cmd = require('node-cmd');

module.exports = function(url) {
    return new Promise(function(resolve, reject) {
        cmd.get(
            'casperjs casper.js ' + url, // casper takes args to run the script
            function(err, data, stderr){
                if (err) {
                    reject(err);
                    return;
                }
                var obj = JSON.parse(data);
                resolve(obj);
            }
        );
    });
}