javascript - Phantom.js 中的 setTimeout

标签 javascript node.js meteor phantomjs

下面的代码希望 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()

            })
        })
    })
})

setTimeout() 替换为 Meteor.setTimeout() 会导致另一个错误:

phantom stdout: ReferenceError: Can't find variable: Meteor

最佳答案

page.evaluate() 是 PhantomJS 的沙盒页面上下文。它无法访问外部定义的变量。如果您需要超时,那么您需要对 page.evaluate() 进行两次调用,因为您无法从异步函数 (explanation) 返回任何内容:

page.evaluate(function() {
    ...
    element.dispatchEvent( event );
}, function() {
    setTimeout(function() {
        page.evaluate(function() {    
            return document.documentElement.outerHTML
        }, function(html) {
            doSomething()
        })
    }, 5000)
})

除了使用第二个 page.evaluate() 调用,您可以通过直接访问定义的内容来缩短代码 here :

setTimeout(function() {
    page.get("content", function(content) {
        doSomething()
    })
}, 5000)

关于javascript - Phantom.js 中的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950627/

相关文章:

javascript - 导入 ECMAScript 6 时为 "Uncaught SyntaxError: Cannot use import statement outside a module"

node.js - Nodemon 环境变量缓存

node.js - NodeJs 无法捕获错误

meteor - 如何正确处理 dom 为 Meteor 做好准备

Meteor 自动形成添加额外输入

javascript - ReactJS 和 Meteor : Generating <select> options?

javascript - 单击按钮开始的 SVG 路径动画

javascript - Django/Jquery/Javascript - 如何使用 url 参数预填充表单(自动填充表单)

javascript - Jquery UI 日期选择器日期格式

node.js - 如何在 Express/node js 中发送错误响应?