栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在CasperJS中打开新标签页

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在CasperJS中打开新标签页

通常,这是不可能的,因为Casper脚本只能在一个phantomjs运行时中运行。就您而言,这似乎是可能的。

注意: 因为这依赖于第二个Casper实例,所以不能在Casper 测试 环境中使用它。

您可以

casper2
在外部Casper实例(
casper1
)的一个步骤中创建一个新的Casper实例()。然后,您必须指示
casper1
等待
casper2
实例完成,因为casper本质上是异步的。请记住,这就像一个新选项卡,因此实例将共享缓存,cookie和存储。

这是一个示例脚本:

var casper1 = require('casper').create();var casper2done = false;casper1.start("http://www.example.com").then(function(){    casper1.capture("casper1_1.png");    var casper2 = require('casper').create();    casper2.start("http://stackoverflow.com/contact").then(function(){        casper1.echo(casper2.getCurrentUrl(), casper2.getTitle());        casper2.capture("casper2.png");    }).run(function(){        this.echo("DONE 2");        casper2done = true;    });}).waitFor(function check(){    return casper2done;}).then(function(){    casper1.echo(casper1.getCurrentUrl(), casper1.getTitle()); // Comment to fix answer (min 6 chars)    casper1.capture("casper1_2.png");}).run(function(){    this.echo("DONE");    this.exit();});

在这里,我使用Promise链接/构建器模式。您甚至可以创建自己的函数来隐藏复杂性并使其可重复使用:

var casper = require('casper').create();// IIFE to hide casper2done variable(function(casper){    var casper2done = false;    casper.newTab = function(url, then, timeout){        if (typeof url !== "string" || typeof then !== "function") { throw "URL or then callback are missing";        }        this.then(function(){ var casper2 = require('casper').create(); casper2.start(url).then(then).run(function(){     casper2done = true; });        }).waitFor(function check(){ return casper2done;        }, null, null, timeout).then(function(){ casper2done = false;        });        return this;    };})(casper);casper.start("http://www.example.com").newTab("http://stackoverflow.com/contact", function(){    // this is casper2    this.echo(this.getCurrentUrl(), this.getTitle());    this.capture("casper2_1.png");    this.thenClick("a#nav-askquestion");    this.then(function(){        this.echo(this.getCurrentUrl(), this.getTitle());        this.capture("casper2_2.png");    });}, 15000).then(function(){    // this is casper    this.echo(casper.getCurrentUrl(), casper.getTitle());    this.capture("casper1.png");}).run(function(){    this.echo("DONE");    this.exit();});

您可以在 子级 Casper实例中使用多个步骤,但不要忘记指定良好的超时时间。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/403903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号