0

我正在尝试将这个 google feed 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

我试过定义 var google;就在包含但没有运气之后。一般来说,我是 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 回答