2012-09-23 57 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