2012-09-23 61 views
7

我正在尝试导航到从脚本本身创建的网址。Casperjs无法动态打开网址?

此示例代码不起作用(我有)预期。想不通为什么:(

var casper = require('casper').create({ 
    viewportSize:{ 
     width:1024, height:768 
    }, 
    pageSettings:{ 
     userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11' 
    }, 
    verbose:true 
}); 

casper.on('open', function (location) { 
    console.log(location + ' loaded'); 
}); 

casper.start('http://www.google.com', function() { 
    this.test.assertTitle('Google', 'Google homepage title is the one expected'); 
}); 

casper.mytest = ''; 

casper.then(function() { 
    casper.mytest = 'http://www.yahoo.com'; 
}); 

casper.thenOpen(casper.mytest, function() { 
    this.test.assertTitle('Yahoo', 'Yahoo homepage title is the one expected'); 
}); 

casper.run(function() { 
     casper.exit(); 
    } 
); 

其结果是,第二页不会加载:

http://www.google.com loaded 
PASS Google homepage title is the one expected 
loaded  
FAIL Yahoo homepage title is the one expected 
# type: assertTitle 
# subject: "" 
# expected: "Yahoo" 

回答

10

我认为,对于你的问题的原因是,在那一刻,当你注册thenOpen步雅虎变量casper.mytest是空的。这个值在这一刻进入了CasperJS的地图的步骤,也不要紧,你改变源变量在之前的步骤。

博客文章Webscraping with CasperJS and PhantomJS可能会有所帮助一个这是一个获取动态构建的url的例子。

+1

谢谢!事实上,如果我在this(){}中使用this.open(),它就可以工作。这很令人不安,因为我担心它会导致非常丑陋的代码,因为我的项目扩大了:( – johnjohn

+0

@johnjohn,前一段时间我做了一个CasperJS的补丁(不是一件小事),它使它工作一步一步(临时)的方式,你可能会根据你的需要做相同的事情,我的版本的问题是,它是前一段时间,现在已经过时,我不打算端口这到最新的CasperJS。 – Stan