等待PhantomJS评估中的DOMContentLoaded()

时间:2015-07-16 22:20:59

标签: javascript phantomjs

page.evaluate()中的JavaScript代码未执行。也许您需要在执行前设置延迟?

var page = require("webpage").create(),
    system = require("system"),
    urls = "http://www.domaines.com",
    useragents = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36",
    w = 600,
    h = 800,
    cookie = phantom.addCookie({
        'name'     : 'uhash', 
        'value'    : '8bb0c9ebcb5781g55196a1ff08c41b4d',
        'domain'   : '.domaines.com',
        'path'     : '/',                
        'httponly' : false,
        'secure'   : false
    });
page.viewportSize = { width: w, height: h };
page.settings.userAgent = useragents;
page.open(urls, function(status){
    if(status !=='success'){
        phantom.exit();
    }else{
        page.cookie;
        page.evaluate(function(){
            function load(){
                var links = document.querySelectorAll('a.link');
                Array.prototype.forEach.call(links, function(e){ 
                    e.click();
                });
            }
            document.addEventListener('DOMContentLoaded', load);
        });

        window.setTimeout(function () {
            page.render('s.png');
            phantom.exit();
        }, 200);
    }
});

1 个答案:

答案 0 :(得分:0)

PhantomJS的page.open()是一个异步函数。最早在完全传输和解析对页面请求的响应时调用其回调。在调用回调时没有明确定义,但根据经验我会说,一旦所有直接资源也被加载(而不是异步资源),它总会被调用。

这意味着在页面上触发DOMContentLoaded事件后很长时间调用回调。这反过来意味着如果您在激活后注册DOMContentLoaded,您的事件处理程序将永远不会触发。

现在看起来像这样:

page.evaluate(function(){
    var links = document.querySelectorAll('a.link');
    Array.prototype.forEach.call(links, function(e){ 
        e.click();
    });
});

问题是element.click()在大多数网页上都不起作用。问题PhantomJS; click an element为这种困境提供了多种解决方案。你这样做:

page.evaluate(function(){
    var links = document.querySelectorAll('a.link');
    Array.prototype.forEach.call(links, function(e){
        var ev = document.createEvent('MouseEvents');
        ev.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, 
                false, false, false, false, 0, null);
        e.dispatchEvent(ev);
    });
});
相关问题