0

このGoogleフィードAPIの例を、Phantomjsで動作するように翻訳しようとしています。Phantomjsの例に従って、次のようになります。

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

私はvargoogleを定義しようとしました。インクルードの直後ですが、運がありません。私はPhantomjsとjs全般に不慣れです。どんなポインタでも大歓迎です。

4

1 に答える 1

0

したがって、「includeJs」からのコールバックの使用方法に問題があります。

あなたが想定しているその機能は、ページのコンテキストで実行されます。そうではありません。メインコンテキストで実行されます。

ページにライブラリを挿入しました: 結構です。さて、あなたはそのページ内で「Stuff」をしたいと思うでしょう。関数を使用する必要があります:

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

また、次の結果を受け取りたいと思われます。

feed.load()

コールバックで。それは問題ありませんが、ギャップを埋める必要があります。ページ コンテキストのコールバックは、ファントム コンテキストでは呼び出すことができません (まだ!)。ドキュメントを少し読んで、ソリューションをどのように考え出すかを確認する必要があります。

念のため: への呼び出し

page.evaluate()

JSON およびその他の JS 単純型 (文字列、数値、ブール値) を返すことができます。これが「ドア」になるはずです。

于 2012-06-05T09:34:45.267 に答える