将参数从php传递到casperjs/fontomjs


Pass parameter from php to casperjs/phantomjs

编辑:我回答了自己的问题,请参阅下面的编辑。

原件:我在web服务器上安装了phantomjs和casperjs,它们都运行良好。我计划创建的脚本在我的网站上的用户输入上重新登录,然后将其传递给casperjs脚本。经过一番周旋之后,我注意到我被困在了用户输入这一非常基本的任务上。如何将变量从php传递到casperjs?

请注意,以下只是测试脚本。

我的php脚本

$user_input = $_POST['user_input'];
putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");
exec('/usr/local/bin/casperjs hello.js 2>&1',$output);
print_r($output);

hello.js

var user_input = "http://example.com/";
var casper = require('casper').create({
  verbose: true,
  logLevel: 'error',
  pageSettings: {
    loadImages: false,
    loadPlugins: false
  }
});
casper.start(user_input, function() {
    this.echo(this.getTitle());
});
casper.run();

那么我该如何将$user_input传递给hello.js呢?我的目标是让用户可以输入一个url,然后对其进行抓取。

我自己找到了答案。

phantomjs和casperjs似乎支持命令行参数http://phantomjs.org/api/system/property/args.html

我的剧本现在是这样的。

test.php

$user_input = $_POST['user_input'];
putenv("PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs");
exec('/usr/local/bin/casperjs hello.js $user_input 2>&1',$output);
print_r($output);

hello.js

var system = require('system');
var args = system.args;
var address = args[4]; //In my case 4 was the argument for $user_input, yours might be different, depending on your server setup.
var casper = require('casper').create({
  verbose: true,
  logLevel: 'error',
  pageSettings: {
    loadImages: false,
    loadPlugins: false
  }
});
casper.start(address, function() {
    this.echo(this.getTitle());
});
casper.run();