2015-10-21 52 views
0

我想從CasperJS的網站上抓取不同網頁的HTML鏈接。在CapserJS中使用document.querySelectorAll的正確方法是什麼?

在我的瀏覽器地址欄(Firefox/Chrome)中,這項工作非常好,並打開我正在尋找的所有鏈接。

javascript:document.querySelectorAll('a[href^="/page"]').click(); 

然而,當我嘗試運行使用下面的代碼CasperJS類似的東西,我得到了很多不屬於上述一致的錯誤。

var pageNodes = this.evaluate(function() { 
    return document.querySelectorAll('a[href^="/page"]'); 
}); 

console.log(typeof(pageNodes)); //Shows object 
console.log(pageNodes.length); //Shows 11, which is correct 

var links = []; 

for(var i = 0; i < pageNodes.length; i++) { 
    console.log(i); 
    console.log(pageNodes[i].href); 
    links.push(pageNodes[i].href); 
}; //pageNode[0].href shows the correct link. pageNode[1] is a null for some reason when it shouldn't be! 

我也試過上面的數組原型,但結果相同!任何人都可以幫我弄清楚什麼是錯的?

var pageArray = this.evaluate(function(pageNodes) { 
    return Array.prototype.splice(pageNodes, 0); 
}); //Gives the same problem, since pagesNodes[1] is null. 
+0

你錯過了在線#3關閉paren – rgthree

+0

糟糕。在輸入問題時輸入錯字。問題仍然存在.... – user2843816

回答

0

PhantomJS有兩個上下文,由於CasperJS是建立在它上面的,它有相同的限制。這意味着對頁面上下文的訪問是沙盒化的,你不能傳遞任意對象。該documentation這樣說:

注:參數和返回值的evaluate功能必須是一個簡單的原始對象。經驗法則:如果它可以通過JSON序列化,那麼它很好。

閉包,功能,DOM節點等將不是工作!

如果您要訪問的每一個環節的href屬性,那麼你必須構建,可外面傳遞或從頁面上下文只打印原始對象:

+0

我試過這個 - 將其轉換爲數組,但仍然無法使用!我錯過了什麼?函數getLinks(選擇器){var pageLinks = document.querySelectorAll(selector);返回Array.prototype.map.call(pageLinks,function(e){return e.getAttribute('href');}); }函數(){pages = this.evaluate(getLinks,'a'); require('utils').dump(頁面); //頁面仍然爲空,不知道爲什麼!}); – user2843816

+0

確保通過截圖('casper.capture(filename)')加載頁面。此外,請註冊到'resource.error','page.error','remote.message'和'casper.page.onResourceTimeout'事件([Example](https://gist.github.com/artjomb/4cf43d16ce50d8674fdf #文件2_caspererrors-JS))。也許有錯誤。 –

相關問題