2012-06-05 65 views
0

我正在嘗試將Google Feed API的this example翻譯成Phantomjs。繼從Phantomjs的example我有以下幾點:使用Phantomjs消費Google Feed API

var page = require('webpage').create(); 

page.onConsoleMessage = function(msg) { 
    console.log(msg); 
}; 

// Our callback function, for when a feed is loaded. 
function feedLoaded(result) { 
    if (!result.error) { 
    // Loop through the feeds, putting the titles onto the page. 
    // Check out the result object for a list of properties returned in each entry. 
    // http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON 
    for (var i = 0; i < result.feed.entries.length; i++) { 
     var entry = result.feed.entries[i]; 
     console.log(entry.title); 
    } 
    } 
} 


page.includeJs("http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0", function() { 
    google.load("feeds", "1"); 
    var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml"); 
    feed.includeHistoricalEntries(); // tell the API we want to have old entries too 
    feed.setNumEntries(250); // we want a maximum of 250 entries, if they exist 

    // Calling load sends the request off. It requires a callback function. 
    feed.load(feedLoaded); 

phantom.exit(); 
}); 

輸出說:

ReferenceError: Can't find variable: google 

我試圖定義VAR谷歌;包括後但沒有運氣。一般來說,我是Phantomjs和js的新手。任何指針非常讚賞。

回答

0

因此,您使用「includeJs」回調的方式存在問題。

您假設的函數是在頁面的上下文中執行的:不是。它在主要上下文中執行。

您已經在頁面中注入了一個庫:很好。現在,我想,你想在該頁面中做「Stuff」。 你要使用的功能:

page.evaluate(function, arg1, arg2, ...); 

而且,我知道你想收到的結果:

feed.load() 

在回調。這很好,但你需要彌補差距:頁面上下文中的回調不能在幻像環境中調用(還!)。您需要閱讀一些文檔,看看您想如何提出解決方案。

裸記住:調用

page.evaluate() 

可以返回JSON和其他JS簡單類型(字符串,數字,布爾值):這應該是你的 「門」。

+0

謝謝我已經包括評估調用,並刪除回調,因此不需要橋接,但現在我沒有從腳本得到任何輸出... https://gist.github.com/2874110 –

+0

喜歡我的答案,不是嗎? :) – Detro

+0

你沒有真正回答這個問題。如果你正在釣魚,你必須做得比這更好。 –