Nyx*_*nyx 11 javascript node.js phantomjs meteor
下面的代码希望Phantom.js加载页面,单击按钮并等待5秒钟,然后返回页面的HTML代码.
问题:但是,使用setTimeout()创建5秒延迟会导致
page.evaluate函数返回null到回调函数而不是HTML.
myUrl = 'http://www.google.com'
var phantom = Meteor.npmRequire('phantom')
phantom.create = Meteor.wrapAsync(phantom.create)
phantom.create( function(ph) {
ph.createPage = Meteor.wrapAsync(ph.createPage)
ph.createPage(function(page) {
page.open = Meteor.wrapAsync(page.open)
page.open(listingUrl, function(status) {
console.log('Page loaded')
page.evaluate = Meteor.wrapAsync(page.evaluate)
page.evaluate(function() {
// Find the button
var element = document.querySelector( '.search-btn' );
// create a mouse click event
var event = document.createEvent( 'MouseEvents' );
event.initMouseEvent( 'click', true, true, window, 1, 0, 0 );
// send click to element
element.dispatchEvent( event );
// Give page time to process Click event
setTimeout(function() {
// Return HTML code
return document.documentElement.outerHTML
}, 5000)
}, function(html) {
// html is `null`
doSomething()
})
})
})
})
Run Code Online (Sandbox Code Playgroud)
更换setTimeout()有Meteor.setTimeout()原因的另一个错误:
phantom stdout: ReferenceError: Can't find variable: Meteor
Run Code Online (Sandbox Code Playgroud)
page.evaluate()是PhantomJS的沙盒页面上下文.它无法访问外部定义的变量.如果你需要超时,那么你需要做两次调用page.evaluate(),因为你不能从异步函数返回任何东西(解释):
page.evaluate(function() {
...
element.dispatchEvent( event );
}, function() {
setTimeout(function() {
page.evaluate(function() {
return document.documentElement.outerHTML
}, function(html) {
doSomething()
})
}, 5000)
})
Run Code Online (Sandbox Code Playgroud)
page.evaluate()您可以通过直接访问此处定义的内容来缩短代码,而不是使用第二个调用:
setTimeout(function() {
page.get("content", function(content) {
doSomething()
})
}, 5000)
Run Code Online (Sandbox Code Playgroud)