本文所述均在ubuntu环境下。
预装:npm(sudo apt-get install nodejs)
npm预装:java(?)
---------------------------------------------------------------------------
下载或者安装路径放到/usr/local/lib/下,否则可能会有权限问题,
file_exists('/usr/local/bin/phantomjs')
is_executable('/usr/local/bin/phantomjs')
这两行代码可以查看是否配合成功,如果成功返回true,否则返回false
---------------------------------------------------------------------------
安装Casperjs
打开命令行,输入:
输出版本号,即安装成功
---------------------------------------------------------------
安装方法2:phantomjs下载:http://phantomjs.org/download.html
casperjs下载:https://github.com/casperjs/casperjs
下载完成后,执行ln -s /phnatomjs/bin/phantomjs /usr/local/bin/phantomjs
ln -s /casperjs/bin/casperjs /usr/local/bin/casperjs
----------------------------------------------------------------
var casper = require('casper').create();
casper.start('http://www.baidu.com/');
casper.then(function() {
this.echo('First Page: ' + this.getTitle());
});
casper.run();
本人再使用php执行phantomjs命令的时候报错“QXcbConnection: Could not connect to display”, 本人才疏学浅,google两周未果,遂使用casperjs,直接执行成功,所以使用php执行phantomjs失败的时候, 不要埋头苦寻问题根源,不妨先试试casperjs
php代码:
putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");//引入phantomjs
exec("/usr/local/bin/casperjs /dir/test.js");//此处我使用的都是绝对路径
如果执行成功,$op输出返回值;如果执行失败,$op输出错误信息;$er输出命令执行状态,为ubuntu命令行执行状态, 例如134,127,如果此类报错,并且代码无误,我认为需从ubuntu执行命令行返回status入手解决问题。
casperjs输入错误信息:
在脚本中加入如下代码:
// http://docs.casperjs.org/en/latest/events-filters.html#remote-message
casper.on("remote.message", function(msg) {
this.echo("Console: " + msg);
});
http://docs.casperjs.org/en/latest/events-filters.html#page-error
casper.on("page.error", function(msg, trace) {
this.echo("Error: " + msg);
// maybe make it a little fancier with the code from the PhantomJS equivalent
});
// http://docs.casperjs.org/en/latest/events-filters.html#resource-error
casper.on("resource.error", function(resourceError) {
this.echo("ResourceError: " + JSON.stringify(resourceError, undefined, 4));
});
// http://docs.casperjs.org/en/latest/events-filters.html#page-initialized
casper.on("page.initialized", function(page) {
// CasperJS doesn't provide `onResourceTimeout`, so it must be set through
// the PhantomJS means. This is only possible when the page is initialized
page.onResourceTimeout = function(request) {
console.log('Response Timeout (#' + request.id + '): ' + JSON.stringify(request));
};
});
调整完毕记得注释该段代码
欢迎交流cauyylAT163.com