如何在 node.js 中使用 CasperJS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9459097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:14:32  来源:igfitidea点击:

How to Use CasperJS in node.js?

node.jsphantomjs

提问by atian25

I would like to use CasperJS in node.js.

我想在 node.js 中使用 CasperJS。

I have referred to the following URL's to use CasperJS in node.js:

我参考了以下 URL 以在 node.js 中使用 CasperJS:

With the help of the above URLs I have written the following code:

在上述 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();
});


When I run this code, I got the following error:

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

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

采纳答案by atian25

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

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

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

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

I wan to use casperjs in nodejs. and refs to: https://github.com/sgentle/phantomjs-nodeand http://casperjs.org/index.html#faq-executable

You can't run CasperJS that way; QtWebKit and V8 don't share the same js environment (and event loop), so your node.js app won't be able to load and use a CasperJS module. You have to run your CasperJS script separately using a subprocess call, like this one on github. I don't plan to make CasperJS compatible with phantomjs-node because it uses alert()-based dirty hacks I'm not easy with.

Cheers, -- Nicolas Perriault

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

你不能那样运行 CasperJS;QtWebKit 和 V8 不共享相同的 js 环境(和事件循环),因此您的 node.js 应用程序将无法加载和使用 CasperJS 模块。你必须使用子进程调用单独运行你的 CasperJS 脚本, 就像 github 上的这个。我不打算让 CasperJS 与 phantomjs-node 兼容,因为它使用 alert()基于我不容易处理的脏黑客。

干杯,——尼古拉斯·佩里奥

回答by NiKo

You can use SpookyJSto drive CasperJS from Node.

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

回答by Hemerson Varela

CasperJS includes a web server to talk to the outside world. Node (using request, superagentetc) can now talk to casper over HTTP.

CasperJS 包括一个与外界对话的网络服务器。节点(使用requestsuperagent等等),现在可以跟卡斯帕通过HTTP。

In scraper.js:

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();
    });
});

You can now run scraper.jsas a web server:

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

chmod +x scraper.js
./scraper.js

You should run it as a Linux service just like you would for a node app.

您应该将其作为 Linux 服务运行,就像运行节点应用程序一样

回答by a paid nerd

One solution (which worked for me) is to start and stop your server on a per-test basis. For example, I have a runtests.coffeewhich looks like:

一种解决方案(对我有用)是在每次测试的基础上启动和停止服务器。例如,我有一个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

And my CasperJS tests in tests/look like:

我的 CasperJS 测试tests/如下所示:

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()

回答by Allen Wong

I tried to run casper by node cron job too, here's my solution

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

in casper.js echo your response:

在 casper.js 中回应你的回应:

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

use node-cmd in node file casper_wrapper.js:

在节点文件 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);
            }
        );
    });
}

回答by Russ Clarke

It basically means that your script can't find Casper; have you checked the path and made sure that

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

/opt/libs/casperjs 

and:

和:

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

Are accessible by a website user ? considering the location it's probably not likely. /opt is a unix path, but the website will be looking in {websiterootpath}/opt.

网站用户可以访问吗?考虑到位置,这可能不太可能。/opt 是 unix 路径,但网站将在 {websiterootpath}/opt 中查找。

I'd create a subfolder 'casperjs' in the root folder of your website and copy the contents of

我会在您网站的根文件夹中创建一个子文件夹“casperjs”并复制其中的内容

/opt/libs/casperjs 

To there. Then change your paths from

到那里。然后改变你的路径

/opt/libs/casperjs

To

/casperjs