【问题标题】:Waiting for DOMContentLoaded in PhantomJS's evaluate()在 PhantomJS 的 evaluate() 中等待 DOMContentLoaded
【发布时间】:2015-07-16 22:20:59
【问题描述】:

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);
    }
});

【问题讨论】:

    标签: javascript phantomjs


    【解决方案1】:

    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);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 2013-05-24
      • 2012-07-05
      • 1970-01-01
      • 2017-07-05
      相关资源
      最近更新 更多