CasperJS 运行 可以在同一进程中使用多个实例吗?

Can CasperJS run multiple instances in the same process?

我正在尝试 运行 在同一个进程中使用多个 CasperJS 实例,我的测试代码如下所示:

['user1,pass1', 'user2,pass2'].forEach(function( account ) {
    var casperInstance = require('casper').create({
          verbose: true,
          logLevel: "debug",
            webSecurityEnabled: false,
          pageSettings: {
               loadImages:  true,
               loadPlugins: true,
               userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
          }
    });

  runit(casperInstance, account);
});

function runit(casperi, account) {

    casperi.options.viewportSize = {width: 1920, height: 1080};

    var account = account.split(',');

    casperi.start( 'https://www.example.com/login/', function ( ) {
        var x = require('casper').selectXPath;

        this.fill('form.loginForm', {
            'username': account[0], 
            'password': account[1]
        }, false);

        this.click(x('//*[text()="Log in"]'));

    }).waitForUrl(/https:\/\/www.example.com\/$/, function then() { // have to use this because the form is submitted with ajax, is there a better way?
        //this.echo(this.getHTML());
    this.echo('Logged in');
    }, function OnTimeout() {
    this.echo('Login Failed');
    }, 20000);

    casperi.run();
}

阵列上只有一个帐户时它工作正常,但有两个或更多帐户时,它总是超时,我不认为我的代码是 运行宁多个 casper 实例,因为如果我更换所有登录代码只打印 html (或其他任何东西)它只打印一次。

有没有办法在同一个进程上 运行 多个 CasperJS 实例,或者创建启动器启动多个进程的唯一解决方案?

是的,你可以使用多个 casper 实例,但你必须记住它们都 运行 在同一个 PhantomJS 进程中,这相当于一个桌面浏览器 window.您可以有多个选项卡,但这些选项卡将共享相同的 cookies/localStorage,因此会共享相同的会话。

因为您正在尝试测试登录,这可能是通过 cookie 实现的,所以这是行不通的。第一个"tab"打开登录页面,尝试登录,可能会成功。但是第二个 "tab" 同时尝试同样的事情。服务器可能会检测到这一点,就好像用户双击了一样,并且没有继续登录或只是其中一个登录(此时只是猜测)。

关键是如果你需要不同的会话,那么你不能在一个进程中使用多个casper实例。显而易见的解决方案是让测试 运行 用于多个 PhantomJS 实例(可能是某种池)中的每个用户名和密码组合。