PHP 正在使用 CasperJS 调用exec()
命令。 CasperJS 完成检索网页部分内容等工作后,如何将检索到的数据返回给 PHP?
我认为将数据从 CasperJS 传输到另一种语言(例如 PHP)的最佳方法是将 CasperJS 脚本作为服务运行。由于 CasperJS 是在 PhantomJS 上编写的,因此 CasperJS 可以使用 PhantomJS 的嵌入式 Web 服务器模块(称为 Mongoose)。
有关嵌入式 Web 服务器如何工作的信息,请参阅here http://phantomjs.org/api/webserver/
下面是有关 CasperJS 脚本如何启动 Web 服务器的示例。
//define ip and port to web service
var ip_server = '127.0.0.1:8585';
//includes web server modules
var server = require('webserver').create();
//start web server
var service = server.listen(ip_server, function(request, response) {
var links = [];
var casper = require('casper').create();
function getLinks() {
var links = document.querySelectorAll('h3.r a');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('href')
});
}
casper.start('http://google.fr/', function() {
// search for 'casperjs' from google form
this.fill('form[action="/search"]', { q: 'casperjs' }, true);
});
casper.then(function() {
// aggregate results for the 'casperjs' search
links = this.evaluate(getLinks);
// now search for 'phantomjs' by filling the form again
this.fill('form[action="/search"]', { q: 'phantomjs' }, true);
});
casper.then(function() {
// aggregate results for the 'phantomjs' search
links = links.concat(this.evaluate(getLinks));
});
//
casper.run(function() {
response.statusCode = 200;
//sends results as JSON object
response.write(JSON.stringify(links, null, null));
response.close();
});
});
console.log('Server running at http://' + ip_server+'/');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)