通过PhantomJS调用时找不到模块'casper'

chi*_*nko 8 phantomjs casperjs

我在C:\ xampp\htdocs\phantom中安装了PhantomJS,并且我在这个文件夹C:\ xampp\htdocs\casper中安装了CasperJS

当我尝试使用phantomjs test.js命令在casper站点上运行这些示例代码时:

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();
}, '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();
Run Code Online (Sandbox Code Playgroud)

它告诉我一个错误:

错误:找不到模块'casper'

我做错了什么?

Art*_* B. 7

如果你想通过PhantomJS运行CasperJS(因为你调用phantomjs test.js),你需要在脚本的开头有一些引导代码:

phantom.casperPath = 'path/to/node_modules/casperjs';
phantom.injectJs('path/to/node_modules/casperjs/bin/bootstrap.js');
Run Code Online (Sandbox Code Playgroud)

请记住,即使在Windows上,您也需要使用正斜杠.

如果您需要测试环境,那么您还需要以下行:

phantom.casperTest = true;
Run Code Online (Sandbox Code Playgroud)

一切都取自这个问题:在幽灵中运行'casperjs test'

虽然这是可能的,但你不应该这样做.您应该通过node_modules/casperjs/batchbin中的可执行文件/批处理文件直接调用CasperJS.