如何通过链接进行循环,并为PhantomJS中的每个站点执行jQuery javascript

我试图build立一个响应式网页devisetesting工具。 我已经成功地捕获了不同设备特定视口大小的链接数组中的每个链接。

但是该工具的另外一个要求是能够将自定义的JavaScript脚本注入到该站点中,等待该脚本完成,然后捕获该页面的状态(例如,有人希望在捕获它之前打开引导模式)。

我一直在使用jQueryGo Node模块来完成我的工作。

到目前为止我已经完成了

我已经设法使其工作,但不能够使用jQuery组件(和我曾尝试使用phantom提供的injectJs和includeJs)。 在下面的代码中使用asyncjs和一些辅助函数。

var $ = require('../node_modules/jquerygo/lib/jquery.go.js'); var async = require('../node_modules/jquerygo/node_modules/async/lib/async.js'); var jqueryCdn = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js'; var links = [{ url: "http://google.com", sitename: "Google", jsinject: function() { var log = document.querySelectorAll('title')[0].innerText; console.log(log); } }, ... ]; var sizes = [{ device: "desktop", userAgent: "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36", width: 1440, height: 1080 }, ... ]; /* * This function wraps WebPage.evaluate, and offers the possibility to pass * parameters into the webpage function. The PhantomJS issue is here: * */ var evaluate = function(page, func) { var args = [].slice.call(arguments, 2); var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}"; return page.evaluate(fn); }; var adjustPageSettings = function(page, size) { page.set( 'viewportSize', { width: size.width, height: size.height } ); $.config.userAgent = size.userAgent; return page; }; $.getPage(function(page) { /** * snaps screenshot of page and safes it * @param siteName * @param device * @param done */ var snapShoot = function(siteName, device, done) { console.log('snapshooting: ' + siteName + ' for ' + device); page.render('screenshot' + siteName + device + '.png', done); }; async.eachSeries(sizes, function(size, done) { async.eachSeries(links, function(link, done) { page = adjustPageSettings(page, size); page.open(link.url, function(status) { if (status == 'success') { async.series([ function(done) { if (typeof link.jsinject == 'function') { evaluate(page, link.jsinject, ''); done(); } else { done(); } }, function(done) { snapShoot(link.sitename, size.device, done); } ], function() { done() }); } else { console.log('couldnt load:' + link.url); } }); }, done); }); }); 

但是,只要我使用jQuery组件如下:

 ... $.getPage(function (page) { page.injectJs(jqueryCdn); .... 

和…

 var links = [ { url: "http://google.com", sitename: "Google", jsinject: function () { var log = $('title').text(); console.log(log); } }, 

我得到一个jQuery没有加载错误:

  phantom stdout: ReferenceError: Can't find variable: $ phantomjs://webpage.evaluate():2 phantomjs://webpage.evaluate():4 phantomjs://webpage.evaluate():4 phantomjs://webpage.evaluate():4 

错误消息说jQuery没有加载到DOM中。

variables名jqueryCdnbuild议您使用远程资源(URL)。 page.injectJs()仅支持本地path。 你需要使用page.includeJs() 。 不要忘记使用callback,否则可能是你的脚本被执行,但jQuery尚未加载到DOM。