且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过命令行将变量作为参数传递给CasperJS脚本?

更新时间:2023-11-07 14:09:34

说明您可以传递命令行参数。


CasperJS附带一个内置的命令行解析器,位于
PhantomJS'的顶部,位于 cli 模块中;它暴露了传递的参数
作为位置和命名选项



但是不用担心操作cli模块解析API,Casper
实例总是包含准备使用 cli 属性,允许轻松
访问所有这些参数。



$ b b

示例代码:

  var casper = require(casper)。 

casper.echo(Casper CLI passed args:);
require(utils)。dump(casper.cli.args);

casper.echo(Casper CLI passed options:);
require(utils)。dump(casper.cli.options);

casper.exit();

执行结果:


$ casperjs test.js arg1 arg2 arg3 --foo = bar --plop anotherarg Casper




  CLI传递的参数:[
arg1,
arg2,
arg3,
anotherarg]
Casper CLI通过选项: {
casper-path:/ Users / niko / Sites / casperjs,
cli:true,
foo:bar,
plop :true}


I'm using PhantomJs, CasperJs, and Js in a js file ran through the cmd.

Imagine we had two files(test1.js, and test2.js). Both files have a url/site variable that directs the test to a particular address. Everytime an environment changed or the target location changed, we would need to update this variable.

To avoid having to update the files, I'd like to pass the values through the command line, as to where to test this.

Is there a way to declare the string variable through the cmd as you run the file?

E.g.:

casperjs test.js "var site='http://google.com';"

The documentation says you can pass command-line parameters.

CasperJS ships with a built-in command line parser on top of PhantomJS’ one, located in the cli module; it exposes passed arguments as positional ones and named options

But no worries for manipulating the cli module parsing API, a Casper instance always contains a ready to use cli property, allowing easy access of all these parameters.

Example code:

var casper = require("casper").create();

casper.echo("Casper CLI passed args:");
require("utils").dump(casper.cli.args);

casper.echo("Casper CLI passed options:");
require("utils").dump(casper.cli.options);

casper.exit();

Execution results:

$ casperjs test.js arg1 arg2 arg3 --foo=bar --plop anotherarg Casper

CLI passed args: [
    "arg1",
    "arg2",
    "arg3",
    "anotherarg" ]
Casper CLI passed options: {
    "casper-path": "/Users/niko/Sites/casperjs",
    "cli": true,
    "foo": "bar",
    "plop": true }